What can use for DateTime::diff() for PHP 5.2?

后端 未结 10 1577
情歌与酒
情歌与酒 2020-11-27 06:18

Is there any function equivalent to DateTime::diff() in PHP 5.2?

My local server is PHP 5.3 and using DateTime::diff(). then I found that my live site uses PHP 5.2 a

相关标签:
10条回答
  • 2020-11-27 06:50

    Spudley's answer doesn't work for me--subtracting any DateTime from another gives 0 on my system.

    I was able to get it to work by using DateTime::format with the 'U' specifier (seconds since Unix epoch):

    $start = new DateTime('2010-10-12');
    $end = new DateTime();
    $days = round(($end->format('U') - $start->format('U')) / (60*60*24));
    

    This works on both my dev system (5.3.4) and my deployment system (5.2.11).

    0 讨论(0)
  • 2020-11-27 06:56

    I use this, seems to work alright - obviously you can add a second parameter to make it more flexible:

    function GetDateDiffFromNow($originalDate) 
    {
        $unixOriginalDate = strtotime($originalDate);
        $unixNowDate = strtotime('now');
        $difference = $unixNowDate - $unixOriginalDate ;
        $days = (int)($difference / 86400);
        $hours = (int)($difference / 3600);
        $minutes = (int)($difference / 60);
        $seconds = $difference;
    
        // now do what you want with this now and return ...
    }
    
    0 讨论(0)
  • 2020-11-27 06:57

    Read the contrib notes in the PHP date_diff page http://us3.php.net/manual/en/function.date-diff.php

    0 讨论(0)
  • 2020-11-27 07:01

    PHP has methods for working with Unix timestamps.

    As has been noted by others, by working with seconds since the Unix date, it is easy to calculate times.

    PHP's strtotime() converts a date to a timestamp:

    $diff = round((strtotime($list['start']) - strtotime($list['finish'])) / 86400);
    

    If you wish to calculate till the current time, time() provides the timestamp of "now":

    $diff = round((time() - strtotime($list['date'])) / 86400);
    

    86400 is the number of seconds in a day.
    If you wish to convert to years use 31557000, which is almost exactly 365.24219 * 86400.

    An added advantage here is that strtotime can take the input date in almost any human readable format, so it is very easy to work with within the code.

    0 讨论(0)
提交回复
热议问题