简体   繁体   中英

Swift: ISO 8601 date from week and year

I am trying to get the date for the first day of the week for a given calendar week and year using Swift.

let calendar = Calendar(identifier: .gregorian)
var dayComponent = DateComponents()
dayComponent.weekOfYear = 7
dayComponent.weekday = 1
dayComponent.year = 2016
var date = calendar.date(from: dayComponent as DateComponents)

First problem is that weekday = 1 will give the Sunday and not ISO 8601 (Monday) so I assume that NSCalendar is not ISO 8601 compatible. But no problem, I can use weekday = 2.

Second problem is that the code above will give 7-Feb-2016 instead of 15-Feb-2016. The problem here is that ISO 8601 defines the first week as the week with the first thursday which is also not used by NSCalendar.

So the question is, is there a way to get the first day of week ISO 8601 compatible with swift?

None of the examples I found are resulting in a ISO compatible date. Thanks!

When working with ISO8601 date components, use the ISO8601 calendar.

The following code gives you February 15, 2016:

let calendar = Calendar(identifier: .iso8601)
let dayComponent = DateComponents(year: 2016, weekday: 2, weekOfYear: 7)
let date = calendar.date(from: dayComponent)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM