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

后端 未结 10 1672
情歌与酒
情歌与酒 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条回答
  •  -上瘾入骨i
    2020-11-27 06:49

    Yes, it's annoying that feature didn't make it into PHP5.2.

    I'll assume you can't upgrade to 5.3? You should look into it; there's very little reason not to upgrade; but I'll assume you can't for whatever the reason.

    First tip: If you only need a diff of less than 24hours, you can simply subtract the two time stamps, and do $time_diff = date('H:i:s',$subtracted_value);

    If you're doing more than 24 hour diffs, but you're okay with just returning the number of days along with the time difference, you can expand on the above technique by doing a modulus calculation on the subtrated value, against the number of seconds in a day (ie 24*60*60, which is 86400)

    $subtracted_value = $date1 - $date2;
    $days_diff = $subtracted_value % 86400;
    $time_diff = date('H:i:s',$subtracted_value);
    

    If you need weeks, you can of course do $days_diff % 7.

    Unfortunately, the manual technique breaks down after weeks, because months and years are variable in length (technically days are too, given daylight saving, but you can probably ignore that, especially as you're only ever going to be one hour out, at the most), but hopefully that's good enough to get you started.

提交回复
热议问题