簡體   English   中英

php DateTime diff - 包括兩個日期范圍?

[英]php DateTime diff - include both dates in range?

我一直在使用 DateTime Diff(在 php 中)來獲取日期對的各種設置 - 要顯示的兩個格式化日期,從日期到現在的差異(例如“開始日期是 3 個月 2 天前”),以及之間的長度兩個日期(“長度為 2 個月 3 天”)。

問題是 DateTime Diff 忽略了其中一天,所以如果開始是昨天,結束是明天,它會給出 2 天,而我想要 3 天,因為這兩個日期都應該包含在長度中。 如果只是幾天,我可以簡單地將結果加 1,但我想使用 Diff 的年/月/日結果,這些結果是在構造時確定的。

我發現獲得所需結果的唯一方法是為開始和結束創建一個 DateTime(以獲取格式化的日期和差異)。 然后取結束日期時間,加上 1 天,然后算出長度。

這有點笨拙,但似乎無法告訴 DateTime Diff 在結果中包含開始日期和結束日期。

DateTime封裝了一個特定的時刻。 “昨天”不是片刻,而是一個時間范圍。 “明天”也一樣

DateTime::diff()不會忽略任何內容; 它只是為您提供兩個時刻之間的確切差異(以天、小時、分鍾為單位)。

如果您想將“明天”和“昨天”之間的差異設為“3 天”,您可以從(“明天”最后一秒后的一秒)中減去“昨天”的第一秒。

像這樣:

// Always set the timezone of your DateTime objects to avoid troubles
$tz = new DateTimeZone('Europe/Bucharest');
// Some random time yesterday
$date1 = new DateTime('2016-07-08 21:30:15', $tz);
// Other random time tomorrow
$date2 = new DateTime('2016-07-10 12:34:56', $tz);

// Don't mess with $date1 and $date2;
// clone them and do whatever you want with the clones
$yesterday = clone $date1;
$yesterday->setTime(0, 0, 0);         // first second of yesterday (the midnight)
$tomorrow = clone $date2;
$tomorrow->setTime(23, 59, 59)               // last second of tomorrow
         ->add(new DateInterval('PT1S'));    // one second

// Get the difference; it is the number of days between and including $date1 and $date2
$diff = $tomorrow->diff($yesterday);

printf("There are %d days between %s and %s (including the start and end date).\n",
     $diff->days, $date1->format('Y-m-d'), $date2->format('Y-m-d')
);

暫無
暫無

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

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