我正在使用NSDateFormatter
将一系列日期转换为一个月内的周数。
我使用的日期格式代码是yyyyMMW
,我读过的所有内容都告诉我 W 将在 1-5 之间。
但是,2013 年 6 月 2 日是星期日(公历中一周的默认开始日),即使一周的开始日期计算正确,它的周数也会报告为 0:
2013-06-03 14:15:45.611 date=20130531, week=2013055, start of week=20130526
2013-06-03 14:15:45.612 date=20130602, week=2013060, start of week=20130602
2013-06-03 14:15:45.612 date=20130603, week=2013061, start of week=20130602
一些快速而肮脏的测试代码来重现上面显示的日志:
NSDateFormatter *dateFormatDaily = [[NSDateFormatter alloc] init];
[dateFormatDaily setDateFormat:@"yyyyMMdd"];
NSDateFormatter *dateFormatterWeekly = [[NSDateFormatter alloc] init];
[dateFormatterWeekly setDateFormat:@"yyyyMMW"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setFirstWeekday:1]; // default but set here for clarity
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setMonth:5];
[dateComponents setDay:31];
[dateComponents setYear:2013];
NSDate *date_1 = [calendar dateFromComponents:dateComponents];
[dateComponents setMonth:6];
[dateComponents setDay:2];
NSDate *date_2 = [calendar dateFromComponents:dateComponents];
[dateComponents setDay:3];
NSDate *date_3 = [calendar dateFromComponents:dateComponents];
NSArray *datesToTest = @[date_1, date_2, date_3];
for (NSDate *date in datesToTest) {
NSString *weekNo = [dateFormatterWeekly stringFromDate:date];
NSDate *beginningOfWeek = nil;
BOOL rc = [calendar rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:NULL forDate:date];
if (rc) {
NSLog(@"date=%@, week=%@, start of week=%@", [dateFormatDaily stringFromDate:date], weekNo, [dateFormatDaily stringFromDate:beginningOfWeek]);
} else {
NSLog(@"Could not calculate beginning of week");
}
}
有任何想法吗?在任何情况下,周数 0对我来说都是错误的。
谢谢