我希望通过以下代码从其编号中获取星期的开始日期:
+ (NSDate *)dateOfWeek:(NSInteger)weekOfYear year:(NSInteger)year {
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setFirstWeekday:2]; // monday
calendar.minimumDaysInFirstWeek = 4; // iso 8601
NSDateComponents *components = [[NSDateComponents alloc] init];
components.year = year;
components.weekOfYear = weekOfYear;
[components setWeekday:2]; // monday
NSDate *date = [calendar dateFromComponents:components];
return date;
}
如果年份= 2017年且weekOfYear = 52(或其他有效数字)日期正确无误:
2017-12-24 21:00:00 +0000
如果年份= 2018年且weekOfYear = 2日期也是正确的:
2018-01-07 21:00:00 +0000
但是如果年份= 2018年且weekOfYear = 1日期不正确:
2018-12-30 21:00:00 +0000
必须 2017-12-31 21:00:00 +0000 。
使用NSDateFormatter获取日期的第二种方法是:
NSString *dateString = [NSString stringWithFormat:@"%li %li", (long)year, (long)weekOfYear];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy ww";
NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(@"%@", [date description]);
但它与year = 2018和weekOfYear = 1相同的问题有效!
我在获取周日日期时遇到了什么问题,或者这是基金会错误?
答案 0 :(得分:1)
这不是基金会的错误。
您需要组件yearForWeekOfYear
才能获得正确的一周:
components.yearForWeekOfYear = year;
日期格式化程序问题实际上是相同的, yearForWeekOfYear 说明符是Y
dateFormatter.dateFormat = @"YYYY ww";