好的,这是我的代码,用于将当前日期格式化为GMT格式并返回日期类型中的值。我在调试时使用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)!
答案 0 :(得分:2)
您的代码都不是必需的。这一行:
let date = Date()
就是你所需要的。这将为您提供当前的日期和时间。
您的错误是使用po
来打印日期。这在显示日期的调试输出的日期使用description
方法,该输出以UTC时间显示日期。
如果您想在当地时间以字符串形式查看日期,请使用DateFormatter
:
let df = DateFormatter()
df.dateStyle = .long
df.timeStyle = .long
let str = df.string(from: date)
print(str)
这将以当地时间显示日期。