簡體   English   中英

將字符串轉換為具有不同時區的日期會給出錯誤的日期

[英]Converting string to date with a different timezone gives the wrong date

所以這:

import Foundation

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
df.timeZone = TimeZone(identifier: "Australia/Currie")!

let todayString = (df.string(from: Date()))
print(todayString)

let today = df.date(from: todayString)!
print(today)

印刷:

2021-02-19
2021-02-18 13:00:00 +0000

作為參考,今天基於我當前時區的日期是 18 日。 因此,當使用將時間提前的澳大利亞時區時,它會正確打印 19 日。

我不明白為什么todaytodayString了一天,因為它是由同一個DateFormatter構造的。 理想情況下,他們都應該打印 19 號,對嗎?

基本上,我想要做的是同時擁有一個日期(來自不同的時區)和它的字符串表示。

如評論中所述, print始終以 UTC(+0000) 顯示Date實例。 例如檢查

let date = Date()
print(date)

要在您當前的語言環境(和時區)中print日期,請寫

print(today.description(with: .current))

暫無
暫無

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

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