简体   繁体   English

Swift:ISO 8601日期(星期和年份)

[英]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. 我正在尝试使用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. 第一个问题是工作日= 1表示星期日,而不是ISO 8601(星期一),因此我认为NSCalendar与ISO 8601不兼容。 But no problem, I can use weekday = 2. 但没问题,我可以使用平日= 2。

Second problem is that the code above will give 7-Feb-2016 instead of 15-Feb-2016. 第二个问题是,上面的代码将给出2016年2月7日,而不是2016年2月15日。 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. 这里的问题是,ISO 8601将第一周定义为具有第一星期四的星期,NSCalendar也未使用该星期。

So the question is, is there a way to get the first day of week ISO 8601 compatible with swift? 因此,问题是,是否有办法使本周第一天的ISO 8601快速兼容?

None of the examples I found are resulting in a ISO compatible date. 我发现的所有示例均未得出与ISO兼容的日期。 Thanks! 谢谢!

When working with ISO8601 date components, use the ISO8601 calendar. 使用ISO8601日期组件时,请使用ISO8601日历。

The following code gives you February 15, 2016: 以下代码为您提供了2016年2月15日:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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