[英]dateComponents returns wrong number of days between two dates
我有兩個約會。 startDate
和endDate
相隔一天。 從打印 function 我得到:
開始日期: startDate
2023-01-01 05:07:33 +0000
: endDate
2023-01-01 17:08:04 +0000
當然這是 UTC,所以日期不准確,但是如果我得到每個日期的Calendar.Component
.day
,那么我分別得到1
和2
,這正是我所期望的。
我正在嘗試使用以下方法計算這兩個日期之間的天數: 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.