NSCalendar 不校正 GMT 时间
NSCalendar does not correct for GMT time
当我计算一天的开始时,得到一个小时的时差。为什么不针对 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"
您的代码应该可以正常工作,您不应该关心时区。正如 Martin R "NSDate is an absolute point in time and does not have a timezone" 已经提到的那样。如果确实需要使用 UTC 时间,您可以将日历 属性 设置为 UTC,以获取任何日期的 UTC 时间的起始日或中午,如下所示:
extension Calendar {
static let utc: Calendar = {
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "UTC")!
return calendar
}()
static let localTime: Calendar = {
var calendar = Calendar.current
calendar.timeZone = .current
return calendar
}()
}
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"
当我计算一天的开始时,得到一个小时的时差。为什么不针对 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"
您的代码应该可以正常工作,您不应该关心时区。正如 Martin R "NSDate is an absolute point in time and does not have a timezone" 已经提到的那样。如果确实需要使用 UTC 时间,您可以将日历 属性 设置为 UTC,以获取任何日期的 UTC 时间的起始日或中午,如下所示:
extension Calendar {
static let utc: Calendar = {
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "UTC")!
return calendar
}()
static let localTime: Calendar = {
var calendar = Calendar.current
calendar.timeZone = .current
return calendar
}()
}
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"