Viewed   98 times

What is the simplest way to get the difference in days between two PHP DateTimes, considering midnight as a day change (just like the DATEDIFF(DAY) SQL function does)?

For example, between today at 13:00 and tomorrow at 12:00, I should get 1 (day), even though the interval is less than 24 hours.

$date1 = new DateTime("2013-08-07 13:00:00");
$date2 = new DateTime("2013-08-08 12:00:00");
echo $date1->diff($date2)->days; // 0

 Answers

4

You could ignore the time portion of the date string

$date1 = new DateTime(date('Y-m-d', strtotime("2013-08-07 13:00:00")));
$date2 = new DateTime(date('Y-m-d', strtotime("2013-08-08 12:00:00")));
echo $date1->diff($date2)->days; // 1
Sunday, August 7, 2022
2

Use DateTime:

$date = '2012-09-09 03:09:00';

$createDate = new DateTime($date);

$strip = $createDate->format('Y-m-d');
var_dump($strip); // string(10) "2012-09-09"

$now = new DateTime();
$difference = $now->diff($createDate, true);
var_dump($difference);

/* object(DateInterval)#3 (8) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(7)
  ["h"]=>
  int(13)
  ["i"]=>
  int(4)
  ["s"]=>
  int(38)
  ["invert"]=>
  int(0)
  ["days"]=>
  int(7)
} */
Monday, August 22, 2022
4

You can use a heredoc, which supports variable interpolation, making it look fairly neat:

function TestBlockHTML ($replStr) {
return <<<HTML
    <html>
    <body><h1>{$replStr}</h1>
    </body>
    </html>
HTML;
}

Pay close attention to the warning in the manual though - the closing line must not contain any whitespace, so can't be indented.

Saturday, September 10, 2022
 
clucle
 
1

Whenever you need to manipulate date/time stamps based on locale, you should use strftime:

switch ($lang) {
    case 'en':
        setlocale(LC_TIME, 'en_CA.UTF-8');
        echo strftime("%B %e, %G");
        break;
    case 'fr':
        setlocale(LC_TIME, 'fr_CA.UTF-8');
        echo strftime("%e %B %G");
        break;
}

Results:

February 11, 2011  // en
11 février 2011    // fr

Of course, you need to have the locales installed on your system. In Ubuntu per example:

bash-4.1$ sudo locale-gen fr_CA.UTF-8
Monday, December 12, 2022
5

In this particular situation. I would

  • Check to see if the Mongo module is loaded (using extension_loaded() or class_exists())
  • If not loaded, try to load the Mongo module using dl()
  • If loading fails, display an error message so the admin can take care of it (STDERR or trigger_error()

Most distributions already ship different versions of php.ini for Web Servers and CLI. Are there other reasons to add another php.ini configuration for script XYZ (in addition to normal configuration)?

Saturday, October 8, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :