当我计算一天的开始时,获得一小时的时差。为什么GMT + 1没有更正?
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
cal.timeZone = NSTimeZone.localTimeZone()
let startOfToday = cal.startOfDayForDate(NSDate())
print(NSTimeZone.localTimeZone())
print(startOfToday)
输出:
"Local Time Zone (Europe/Amsterdam (GMT+1) offset 3600)\n"
"2016-01-14 23:00:00 +0000\n"
答案 0 :(得分:5)
您的代码应该可以正常工作,您不应该关心时区。正如Martin R"已经提到的那样,NSDate是一个绝对的时间点,没有时区"。如果确实需要使用UTC时间,您可以将calendar属性设置为UTC,以便在UTC时间获取startOfDay或中午的任何日期,如下所示:
extension Date {
var noon: Date {
return Calendar.localTime.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
var startOfDay: Date {
return Calendar.localTime.startOfDay(for: self)
}
var noonAtUTC: Date {
return Calendar.utc.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
var startOfDayAtUTC: Date {
return Calendar.utc.startOfDay(for: self)
}
}
print(Date().noon) // "2018-04-30 15:00:00 +0000\n"
print(Date().startOfDay) // "2018-04-30 03:00:00 +0000\n"
print(Date().noonAtUTC) // "2018-04-30 12:00:00 +0000\n"
print(Date().startOfDayAtUTC) // "2018-04-30 00:00:00 +0000\n"
{{1}}