PHP strtotime 日期差异问题

标签 php strtotime date-math

任何人都可以向我解释这个例子中的 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/

相关文章:

PHP/MySQL : strToTime error manipulating dates

javascript - 将在 ajax 调用中工作的 Strtotime 函数

python - Python 中 datetime.datetime 对象的正确 None 或 null 条目是什么?

c++ - boost local_date_time 数学错了吗?

php - 如何按值过滤多维数组(超过两级)?

php - 使用经过验证的数据上传文件

php future 日期显示 1970-04-01 而不是开始日期后 3 个月

javascript - 请解释我在这个 javascript 日期数学中的错误

php - 触发器不起作用 - 在插入之前更改表以添加新列

php - 从 WooCommerce 画廊中删除特色图片