[英]Swift Date function do not work as Expected
我正在嘗試使用Swift 4.1以秒為單位找出兩個日期之間的差異。 這是我使用的代碼
func getDurationInSeconds(date1 :Date) -> Int{
guard let durationInSeconds = Calendar.current.dateComponents([.second], from: Date(), to: date1).second else {
return 0
}
return durationInSeconds
}
從2018-10-09T18:19:00Z生成date1的函數
func dateFromString(stringDate:String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale?
let date = dateFormatter.date(from: stringDate)
return date
}
日期總是比我當前的設備時間少返回一個小時,因此計算無法按預期進行。 如果我當前的設備時間是16:34,則Date()函數將其返回為15:34。
我已經看到Date()返回的時間不是我的時區,而是UTC時間。
目前,如果我傳遞日期09/10/2018 14:25:00並且當前設備時間是09/10/2018 14:20:00 。 我期望此函數返回的值300是兩個日期之間相差60 * 5分鍾 。
但是我返回的值為3900 ,這是因為date函數將日期返回為
09/10/2018 13:20:00而不是14:20
。 因此,持續時間將為1小時+ 300秒差。
包括來自Xcode控制台的示例輸出,執行此代碼時我的設備時間為2018-10-09 17:56:28.565423
(lldb) po date1
▿ 2018-10-09 17:59:00 +0000
- timeIntervalSinceReferenceDate : 560800740.0
(lldb) po durationInSeconds
3731
(lldb) po Date()
▿ 2018-10-09 16:57:04 +0000
- timeIntervalSinceReferenceDate : 560797024.35021996
(lldb)
但是我找不到根據當前時區在兩次之間找到正確持續時間的正確方法。 我該怎么做?
問題不在於Date()返回錯誤的時間。 Date()始終返回當前時間,它並不是真正基於您(任何其他)本地時區的時間。
問題似乎與您用來從日期字符串生成Date對象的dateFormatter有關。
請嘗試使用以下代碼行:
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
// Not necessary as the dateFormatter would take the device's timeZone to be the default.
dateFormatter.timeZone = Calendar.current.timeZone
代替:
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
后者的問題在於,您將“ Z ”指定為零偏移時區(UTC)。 因此,與設備中的UTC的1小時差異導致了這種偏移。
並且,在傳遞日期字符串時,請確保您在末尾跳過“ Z”(例如,應類似於2018-10-09T18:19:00 )。
更新的代碼應該對您有用,並以秒為單位返回預期的差異。
由於您使用的是表示時區中當前時間的字符串,因此請嘗試以下操作:
func getDurationInSeconds(date1: Date) -> Int {
return Int(-date1.timeIntervalSinceNow + TimeZone.current.daylightSavingTimeOffset(for: date1))
}
或者,如果您想在dateFromString(stringDate:)
中dateFromString(stringDate:)
與UTC的時區差異:
func getDurationInSeconds(date1: Date) -> Int {
return Int(-date1.timeIntervalSinceNow)
}
func dateFromString(stringDate:String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let date = dateFormatter.date(from: stringDate)! //I am force-unwrapping for brevity
let adjustedDate = date.addingTimeInterval(-TimeZone.current.daylightSavingTimeOffset(for: date))
return adjustedDate
}
測試
我處於UTC + 1h時區:
let str = "2018-10-09T19:50:00Z" //"2018-10-09T19:50:00Z"
let date1 = dateFromString(stringDate: str)! //"Oct 9, 2018 at 7:50 PM"
Date() //At the time of testing this it is "Oct 9, 2018 at 7:53 PM"
getDurationInSeconds(date1: date1) //213, which is 3 minutes and 33 seconds
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.