简体   繁体   English

日期在不同版本的PHP中返回不同的结果

[英]date returning different results in different versions of php

I have a date A and B . 我有一个日期AB

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. 想一想: strtotime('2014-01-01') - strtotime('2014-01-01') 为零 - 但是date()期望时间戳作为第二个参数。 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 你的London TZ有+01偏移,这就是为什么0点时间戳是01 Jan 1970 01:00:00 - 这就是为什么date('h:i', 0)01:00

Try to set, for example, Moscow zone: 尝试设置,例如, Moscow区域:

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) - 你会看到完全正确的04:04 - 因为莫斯科的当前偏移是+03 (所以03小时+ 64分钟修改)

What date expects as its second parameter is an absolute timestamp, which it then formats in the specified format. 第二个参数的date绝对时间戳,然后以指定的格式进行格式化。 You outputting h:i means you're outputting only the hour:minute part of a complete year, month, day, hour, minute, second timestamp. 您输出h:i表示您只输出完整年份,月份,日期,小时,分钟,第二时间戳的小时:分钟部分。 If you want to format the relative difference between two timestamps, date is the wrong function to use. 如果要格式化两个时间戳之间的相对差异 ,则date是使用的错误函数。 The result is expected, since you're actually dealing with absolute timestamps in timezones . 结果是预期的,因为您实际上处理时区中的 绝对时间戳。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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