2020-12-07 18:21:47 不是完整的日期时间值。缺少可能导致意外或错误结果的时区。
strtotime() 是一个非常古老的函数。更好的方法是 DateTimeImmutable 类。您可以使用DateTimeImmutable::setTime() 设置时间并使用DateTimeImmutable::diff() 获取差异。
$dates = [
new DateTimeImmutable('2020-12-07T00:21:47Z'),
new DateTimeImmutable('2020-12-07T00:21:47-0800'),
new DateTimeImmutable('2020-12-07 00:21:47', new DateTimeZone('+02:00')),
new DateTimeImmutable('2020-03-29 00:21:47', new DateTimeZone('Europe/Berlin')),
];
$timeParts = explode(':', '19:30:00');
foreach ($dates as $date) {
// get a modified copy of the immutable date time
$other = $date->setTime(...$timeParts);
var_dump($other->format(DateTimeInterface::ATOM));
// differences as a DateInterval
$difference = $date->diff($other);
var_dump($difference->format('%h hour(s), %i minute(s)'));
}
输出:
string(25) "2020-12-07T19:30:00+00:00"
string(23) "19 hour(s), 8 minute(s)"
string(25) "2020-12-07T19:30:00-08:00"
string(23) "19 hour(s), 8 minute(s)"
string(25) "2020-12-07T19:30:00+02:00"
string(23) "19 hour(s), 8 minute(s)"
string(25) "2020-03-29T19:30:00+02:00"
string(23) "18 hour(s), 8 minute(s)"
请注意,最后一个结果是 18 小时。这是因为 3 月 29 日是这个时区的夏令时。