gpt4 book ai didi

PHP日期差异错误

转载 作者:可可西里 更新时间:2023-10-31 23:01:24 25 4
gpt4 key购买 nike

$startDate = new DateTime("2016-06-01");
$endDate = new DateTime("2016-06-30");
$diff = date_diff($startDate,$endDate);
$differenceYear = $diff->format("%y");
$differenceMonth = $diff->format("%m");
$difference = $differenceYear*12 + $differenceMonth;
echo $difference;

以上代码将输出 0 作为结果。但是当我将这两个日期更改为 2016-12-01 和 2016-12-31 时,代码给出 1 作为输出。为什么会这样?

当我在线检查这段代码时,php 编辑器给出了正确的答案。但是当我将它复制到我的本地机器时,答案显示错误。在线编辑器将 美国/太平洋 作为时区。我的电脑有 Asia/Kolkata 时区。两者具有相同的 PHP 版本

最佳答案

使用我的默认时区 (Europe/Bucharest),print_r($diff) 产生:

DateInterval Object
(
[m] => 1
[d] => 0
[days] => 30
)
# I removed the other components as they are irrelevant to the question
# and they are 0 anyway.

意思是:“1 月和 0 天”(md 属性),30 总天数(days 属性)。

使用 Asia/Kolkata 作为它打印的默认时区:

DateInterval Object
(
[m] => 0
[d] => 30
[days] => 30
)
# Again, all the other object properties are 0 and irrelevant for the question

这意味着:“0 个月和 30 天”,总共 30 天。


如您所见,总天数(days 属性)相同(30)并且正确。

关于“1 个月零 0 天”“0 个月零 30 天”,两者在同一时间上都是正确的和不正确的。 p>

“一个月” 的定义是什么?它可以是 2831 天之间的任何时间。这意味着,“1 个月零 0 天” 等于 “0 个月零 28 天”“0 个月零 29 天” a.s.o. 同时


题目是“PHP日期差异错误”——PHP日期差异没有错误。这只是术语 "month" 的宽松定义在人类语言和文化中。

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

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