TimeZone Issue swift3

2019-08-16 17:24发布

I have some troubles using the TimeZone in swift.

 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"

Why is it returns the time with adding 2 minutes when I initialize the time zone? How to avoid this?

It has also happening with different time zones. & I did not find anything about this in a documentation.

Thank you in advance!

2条回答
一纸荒年 Trace。
2楼-- · 2019-08-16 17:54

It's a 2 minute offset because, as you've seen, you're using dates in the year 1. On iOS (as on most computing platforms) time zones are defined by the IANA time zone database. There were no time zones in year 1 but the entry for Asia/Seoul contains this:

# Zone  NAME            GMTOFF  RULES   FORMAT  [UNTIL]
Zone    Asia/Seoul      8:27:52 -       LMT     1908 Apr  1

That is, prior to April 1 1908, the GMT offset is 8:27:52, which matches what you're seeing. (I'm not familiar with the history so I don't know why this is the offset-- I'm guessing based on Seoul's longitude in a pre-time zone world).

You're getting year 1 instead of the current year because your dates don't specify a year:

let startDate = date(hour: 13, minute: 00, timeZone: startDate_TimeZone!)

If what you want is 13:00 today, this year, do something like this:

let now = Date()
let now1pm = Calendar.current.date(bySettingHour: 13, minute: 0, second: 0, of: now)

If that's not what you want, please explain further or look at Calendar for other useful methods.

查看更多
smile是对你的礼貌
3楼-- · 2019-08-16 18:05

As Martin pointed out in comments, you are calculating time zones around the year 0001. There is no time zone data going back that far, because there weren't even such things as time zones.

Time zones without a valid date reference are meaningless. Even in modern times, you can get different results for different parts of the year, due to things like daylight saving time.

Specify a valid date in your conversion and it should work correctly.

查看更多
登录 后发表回答