簡體   English   中英

dateComponents 返回兩個日期之間的錯誤天數

[英]dateComponents returns wrong number of days between two dates

我有兩個約會。 startDateendDate相隔一天。 從打印 function 我得到:

開始日期: startDate 2023-01-01 05:07:33 +0000endDate 2023-01-01 17:08:04 +0000

當然這是 UTC,所以日期不准確,但是如果我得到每個日期的Calendar.Component .day ,那么我分別得到12 ,這正是我所期望的。

我正在嘗試使用以下方法計算這兩個日期之間的天數: Calendar.current.dateComponents([.day], from: startDate, to: endDate).day

然而,這正在返回0 我在這里沒有錯什么? 據我了解,因為這個 function 使用的是Calendar ,所以它應該忽略UTC格式並返回1

您使用的 function 計算兩個日期之間的全天數差異,而不是計算它們是否在不同日期

這可以通過以下示例輕松驗證

let endDate = Date.now
let firstDate = Calendar.current.date(byAdding: .hour, value: -23, to: endDate)!
print(Calendar.current.dateComponents([.day], from: firstDate, to: endDate).day!)
let secondDate = Calendar.current.date(byAdding: .hour, value: -24, to: endDate)!
print(Calendar.current.dateComponents([.day], from: secondDate, to: endDate).day!)

哪個打印

0
1個

一個小時也是如此,其中 -59 分鍾返回 0,-60 分鍾返回 1

暫無
暫無

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

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