【发布时间】:2019-11-19 16:25:31
【问题描述】:
我正在使用这些代码行将日期和时间转换为当前时区:
let calendar = Calendar(identifier: .gregorian)
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:Z"
dateFormatter.timeZone = calendar.timeZone
dateFormatter.string(from:currentDate)
print(dateFormatter.string(from: currentDate))
print 输出给了我:
2019-11-19 17:22:55:+0100
我要将日期存储在 Realm 中,那么如何将其转换回 Date()?
编辑;我尝试转换它,但它不起作用:
let calendar = Calendar(identifier: .gregorian)
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:Z"
dateFormatter.timeZone = calendar.timeZone
let dateString = dateFormatter.string(from:currentDate)
let finalDate = dateFormatter.date(from: dateString)
print(dateString) -> Gives me output: 2019-11-19 18:09:05:+0100 - This is the correct time!
print(finalDate!) -> Gives me output: 2019-11-19 17:09:05 +0000
所以finalDate 应该将当前时间存储为Date(),但它没有得到正确的时间。
【问题讨论】:
-
如果您的目标只是存储日期并转换回来,您应该使用 ISO8601 UTC 时间stackoverflow.com/questions/28016578/…
-
@LeoDabus 为什么会这样?
-
您需要用户时区吗?否则只需使用 ISO8601。顺便说一句,如果您没有将日期格式化程序语言环境设置为 en_US_POSIX,您的解析可能会失败
-
您检查了上面评论中的链接吗?顺便说一句,在向用户显示日期时,您可以使用 stackoverflow.com/questions/28332946/…
-
@LeoDabus 我正在创建一个锻炼日记应用,因此我想存储用户保存锻炼的日期和时间。