我正在使用以下代码行将日期和时间转换为当前时区:
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()
,但是不能获得正确的时间。
答案 0 :(得分:0)
DateFormatter双向转换。使用相同的格式化程序,将其转换回来,请使用.date(from:)
let date = dateFormatter.date(from: string)
根据您的评论,您可能会误解日期是什么。日期只不过是距参考时间的秒数而已。它对时区一无所知。它对日历一无所知。它甚至对几分钟或几小时一无所知。自参考时间以来仅 秒(实际上是一个围绕单个Double值的小包装)。
打印日期时,它将调用.description
,作为程序员的便利,它是由默认的DateFormatter生成的,该日期将DateFormatter纯粹用作调试目的而将其转换为人类可读的字符串。该字符串并不意味着Date附带有日历或时区。这只是程序员的便利。程序本身切勿使用它。
如果要处理时区,则必须使用日历来计算各种DateComponent,或使用DateFormatter(使用日历)来生成字符串。
答案 1 :(得分:0)
DateFormatter也可以选择将字符串转换为日期:
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.date(from: yourStringDate)