gpt4 book ai didi

PHP strtotime 日期差异问题

转载 作者:行者123 更新时间:2023-12-02 07:27:55 26 4
gpt4 key购买 nike

任何人都可以向我解释这个例子中的 strtotime 函数有什么问题?我正在尝试计算日期之间的差异。 PHP 5.6.0 (cli)(内置:2014 年 8 月 28 日 08:03:51)当我执行这个循环时,它显示数字 88 两次。

date_default_timezone_set('Europe/London');
for($i=1;$i<=100;$i++){
$daysAfterTime = floor( abs( strtotime('2014-01-01') - strtotime('2014-01-01 +'.$i.' days') )/(60*60*24));
echo $daysAfterTime.'<br/>';
}

最佳答案

strtotime() 不适用于日期数学。 The manual even says so .

Using this function for mathematical operations is not advisable.

天数不完全是 60*60*24 秒等。

如评论中所述,DateTime() 非常更适合此操作,因为它考虑了夏令时、闰年等。这是一种高级方法使用 DateTime() 执行相同的操作, DateInterval() , 和 DatePeriod()对于任何试图弄清楚发生了什么的人来说,这也更加清楚。

$start    = new DateTimeImmutable('2014-01-01', new DateTimeZone('Europe/London'));
$finish = $start->modify('+101 days'); // extra day as the last day is not inclusive
$interval = new DateInterval('P1D'); // interval of one day
$period = new DatePeriod($start, $interval, $finish);
foreach ($period as $date) {
$diff = $start->diff($date);
echo $diff->days . "<br>";
}

Demo

关于PHP strtotime 日期差异问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25755500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com