Objective C NSCalendar dateFromComponents 不处理第 53 周
以下代码根据经过year
和week
计算给定周的前一周编号。
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:year];
[components setWeek:NSWeekCalendarUnit];
[components setWeekOfYear:(week-1)]; //Get the previous week
[components setWeekday:2]; //Monday
[components setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [calendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyyww"];
NSString *newRevision = [formatter stringFromDate:date];
令我惊讶的是,它处理了像 201101(给出 201052)这样的情况,但它不能正确处理有 53 周的年份。例如,对于 201601,它返回 201552 而不是 201153。(根据 http:// 至少应该返回 201153无论如何,en.wikipedia.org/wiki/ISO_week_date。)
我做错了什么吗?我已经进行了追踪以确保输入是正确的。
The following code calculates the previous week number from a given week when passed year
and week
.
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:year];
[components setWeek:NSWeekCalendarUnit];
[components setWeekOfYear:(week-1)]; //Get the previous week
[components setWeekday:2]; //Monday
[components setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [calendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyyww"];
NSString *newRevision = [formatter stringFromDate:date];
I was surprised that this handled cases like 201101 (which gives 201052), but it does not correctly handle years where there are 53 weeks. For example, for 201601 it returns 201552 instead of 201153. (At least it should return 201153 according to http://en.wikipedia.org/wiki/ISO_week_date anyway.)
Am I doing something wrong? I have traced through to make sure the inputs are correct.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您已为日历选择了
NSGregorianCalendar
。尝试使用NSISO8601Calendar
You have the
NSGregorianCalendar
selected for your calendar. Try using theNSISO8601Calendar
我们最终通过一些技巧解决了这个问题。从问题中的维基百科链接中,我们获得了接下来 400 年的所有年份的列表,其中包含 53 周,并将它们硬编码进去(包含明智的评论和“正确”的解决方案)。
它并不理想,但在 Apple 实施 ISO 8601 或 2404 年之前它可以完成这项工作。
We ended up working around the issue with a bit of hack. From the wikipedia link in the question, we got the list of all years with 53 weeks for the next 400 years and hard coded them in (with judicious comments and the 'correct' solution included).
It's not ideal, but it will do the job until either Apple implements ISO 8601 or until the year 2404.
对于 2016 年 1 月 1 日的情况,您应该得到:
当您打印答案时,请使用“YYYY”而不是“yyyy”。
For the case Jan 1st 2016 you should get:
When you're printing your answer use "YYYY" instead of "yyyy".