在以下代碼示例中:
func numberOfDaysBetween(toDate: String) -> Int { // toDate = "2021/12/21"
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy/MM/dd"
let currentDate = Date()
let toDateFormatted = dateFormatter.date(from: toDate)
print ("Current Date: \(currentDate)") // Current Date: 2021-12-21 11:50:12 0000
print ("ToDate: \(toDate)") // ToDate: 2021/12/21
print ("ToDateFormatted: \(toDateFormatted)") // ToDateFormatted: Optional(2021-12-20 13:30:00 0000)
print (dateFormatter.timeZone) // Optional(Australia/Adelaide (fixed (equal to current)))
return 1 // Test value
}
我沒有看到正確的日期。我花了 4 個小時嘗試各種選項,但一直回到相同的輸出。我如何看到下面的預期輸出?
我期待看到以下內容:
print ("Current Date: \(currentDate)") // Current Date: 2021-12-21
print ("ToDate: \(toDate)") // ToDate: 2021/12/21
print ("ToDateFormatted: \(toDateFormatted)") // ToDateFormatted: 2021/12/21
print (dateFormatter.timeZone) // Optional(Australia/Adelaide (fixed (equal to current)))
有趣的是,我在阿德萊德,時間是22:20(晚上10:20)。為什么呼叫 Date() 時時間不同?
uj5u.com熱心網友回復:
func numberOfDaysBetween(toDate: String) -> Int { // toDate = "2021/12/21"
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy/MM/dd"
let currentDate = Date()
let toDateFormatted = dateFormatter.date(from: toDate)
let df = dateFormatter.string(from: toDateFormatted!)
print ("Current Date: \(currentDate)") // Current Date: 2021-12-21 11:50:12 0000
print ("ToDate: \(toDate)") // ToDate: 2021/12/21
print ("ToDateFormatted: \(df)") // ToDateFormatted: Optional(2021-12-20 13:30:00 0000)
print (dateFormatter.timeZone) // Optional(Australia/Adelaide (fixed (equal to current)))
return 1 // Test value
}
試試這個 。您試圖將字串轉換為日期。以便您獲得該格式,您應該更改它所需的字串格式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/388706.html
上一篇:Elasticsearch查詢以獲取一小時前修改的專案
下一篇:更改引導日期選擇器的回傳格式
