【发布时间】:2017-04-02 17:59:39
【问题描述】:
好的,这是我将当前日期格式化为 GMT 格式并以日期类型返回值的代码。我在调试时'po' nowComponent 变量,它显示了当前的本地时区值,但代码块'calendar.date(来自:nowComponents)!'仍然给我一个UTC日期。如何获取本地时区的日期?
var nowComponents = DateComponents()
let date = Date()
nowComponents.year = (calendar as NSCalendar).component(NSCalendar.Unit.year, from: date)
nowComponents.month = (calendar as NSCalendar).component(NSCalendar.Unit.month, from: date)
nowComponents.day = (calendar as NSCalendar).component(NSCalendar.Unit.day, from: date)
nowComponents.hour = (calendar as NSCalendar).component(NSCalendar.Unit.hour, from: date)
nowComponents.minute = (calendar as NSCalendar).component(NSCalendar.Unit.minute, from: date)
nowComponents.second = (calendar as NSCalendar).component(NSCalendar.Unit.second, from: date)
(nowComponents as NSDateComponents).timeZone = TimeZone.current
return calendar.date(from: nowComponents)!
【问题讨论】:
-
我使用 dateFormatter 将日期转换为本地时区,并且成功了!但我喜欢使用 calendar.current 或 calendar.date 来实现日期转换。