简体   繁体   中英

date returning different results in different versions of php

I have a date A and B .

I wanted to get the hours/minutes between them. Like:

date('h:i', strtotime(B) - strtotime(A));

But I get strange results:

echo date('h:i', strtotime('2014-01-01') - strtotime('2014-01-01'));
// echoes: 01:00 (!)


date_default_timezone_set('Europe/London');
$date = new DateTime();
$A = $date->format('Y-m-d H:i:s'); echo '<br />';
$date->modify("+64 minutes");
$B = $date->format('Y-m-d H:i:s'); echo '<br />';
echo date('h:i', strtotime($B) - strtotime($A));
// echoes 02:04 (!)

Live example for the previous code:

Why is this and how to get the expected result?

This is correct behavior

Why? Think of it: strtotime('2014-01-01') - strtotime('2014-01-01') is zero - but date() expects timestamp as second parameter. So that means, you're trying to get date from zero-point timestamp. And that point is different in different timezones. Your London TZ has +01 offset, that's why 0-point timestamp is 01 Jan 1970 01:00:00 - and that's why date('h:i', 0) is 01:00

Try to set, for example, Moscow zone:

date_default_timezone_set('Europe/Moscow');
$date = new DateTime();
$A = $date->format('Y-m-d H:i:s'); 
$date->modify("+64 minutes");
$B = $date->format('Y-m-d H:i:s'); 

echo date('h:i', strtotime($B) - strtotime($A));//04:04

-you'll see exactly 04:04 - because current offset for Moscow is +03 (so 03 hours + 64 minutes modification)

What date expects as its second parameter is an absolute timestamp, which it then formats in the specified format. You outputting h:i means you're outputting only the hour:minute part of a complete year, month, day, hour, minute, second timestamp. If you want to format the relative difference between two timestamps, date is the wrong function to use. The result is expected, since you're actually dealing with absolute timestamps in timezones .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM