簡體   English   中英

PHP DateTime差異返回錯誤的天數

[英]PHP DateTime difference is returning wrong number of days

我有以下代碼,它打印出兩個日期之間的差異:

print_r((new DateTime('2018-01-01'))->diff(new DateTime('2018-11-01')));

print_r((new DateTime('2018-10-01'))->diff(new DateTime('2018-11-01')));

輸出:

DateInterval Object
(
    [y] => 0
    [m] => 10
    [d] => 0
    [h] => 0
    [i] => 0
    [s] => 0
    [f] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 304
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)
DateInterval Object
(
    [y] => 0
    [m] => 1
    [d] => 1
    [h] => 0
    [i] => 0
    [s] => 0
    [f] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 31
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)

如您所見,第一個日期差異正確地返回10個月和0天。 然而,第二個,而不是0天返回1個月,錯誤地返回1個月和1天。

是什么造成的?

令我感到困惑的是,我試圖在幾個PHP沙箱網站上運行此代碼,並且我得到了不一致的結果:

我自己的服務器和https://wtools.io/php-sandbox返回第二個日期的錯誤天數。 但是例如http://sandbox.onlinephpfunctions.com/在第二個日期差異0天正確返回。

這是因為服務器時區。 只需將所有內容設置為UTC,您就應該沒問題。

print_r((new DateTime('2018-10-01', new DateTimeZone('UTC')))->diff(new DateTime('2018-11-01', new DateTimeZone('UTC'))));

https://3v4l.org/PWKiD

沒有時區,它確實是意想不到的價值。 https://3v4l.org/6v0XI

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM