我在 swift 中使用 TimeZone
时遇到了一些麻烦。
func date(hour: Int, minute: Int, timeZone: TimeZone) -> Date {
let components = DateComponents(calendar: Calendar.current, timeZone: timeZone, era: nil, year: nil, month: nil, day: nil, hour: hour, minute: minute, second: 0, nanosecond: 0, weekday: nil, weekdayOrdinal: nil, quarter: nil, weekOfMonth: nil, weekOfYear: nil, yearForWeekOfYear: nil)
return components.date!
}
var startDate_TimeZone = TimeZone.init(identifier:"Asia/Seoul")
var endDate_TimeZone = TimeZone.current
let startDate = date(hour: 13, minute: 00, timeZone: startDate_TimeZone!)
// Returns "Jan 1, 1, 7:02 AM"
let endDate = date(hour: 13, minute: 00, timeZone: endDate_TimeZone)
// Returns "Jan 1, 1, 1:00 PM"
为什么初始化时区时返回的时间加了2分钟?如何避免这种情况?
It has also happening with different time zones. & I did not find anything about this in a documentation.
提前谢谢您!
最佳答案
这是 2 分钟的偏移,因为正如您所见,您使用的是 1 年的日期。在 iOS 上(与大多数计算平台一样),时区由 IANA time zone database 定义。 。第 1 年没有时区,但亚洲/首尔的条目包含以下内容:
# Zone NAME GMTOFF RULES FORMAT [UNTIL]
Zone Asia/Seoul 8:27:52 - LMT 1908 Apr 1
也就是说,1908 年 4 月 1 日之前,GMT 偏移量为 8:27:52,与您所看到的相符。 (我不熟悉历史,所以我不知道为什么会有这样的偏移——我是根据前时区世界中首尔的经度猜测的)。
您将获得第 1 年而不是当前年份,因为您的日期未指定年份:
let startDate = date(hour: 13, minute: 00, timeZone: startDate_TimeZone!)
如果你想要的是今年今天 13:00,请执行以下操作:
let now = Date()
let now1pm = Calendar.current.date(bySettingHour: 13, minute: 0, second: 0, of: now)
如果这不是您想要的,请进一步解释或查看日历
以获取其他有用的方法。
关于swift - swift3时区问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44661268/