我正在尝试使用NSCalendar获取一周的序数,以便我可以计算两个日期之间的周数,但是我使用的方法显示出一些奇怪的行为。
我期待每周日00:00:00开始新的一周,但似乎发生在23:58:45。我已经尝试更改日历的firstWeekday
属性,但这没有任何效果。
示例代码(注意:2014-03-09是星期日)
- (void)testTimeWeeksBegins
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Make NSDates
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.year = 2014;
comps.month = 3;
comps.day = 9;
comps.hour = 23;
comps.minute = 58;
comps.second = 44;
NSDateComponents *compsToAdd = [[NSDateComponents alloc] init];
compsToAdd.second = 1;
NSDate *date23_58_44 = [calendar dateFromComponents:comps];
NSDate *date23_58_45 = [calendar dateByAddingComponents:compsToAdd toDate:date23_58_44 options:0];
// Calculate ordinality of week on both dates
NSUInteger ord23_58_44 = [calendar ordinalityOfUnit:NSWeekOfYearCalendarUnit inUnit:NSEraCalendarUnit forDate:date23_58_44];
NSUInteger ord23_58_45 = [calendar ordinalityOfUnit:NSWeekOfYearCalendarUnit inUnit:NSEraCalendarUnit forDate:date23_58_45];
// Output
NSLog(@"Date is %@ and week number is %d", date23_58_44, ord23_58_44);
NSLog(@"Date is %@ and week number is %d", date23_58_45, ord23_58_45);
}
输出
Date is 2014-03-09 23:58:44 +0000 and week number is 105043
Date is 2014-03-09 23:58:45 +0000 and week number is 105044
我是愚蠢的,错过了一些明显的东西,还是这个错误?我想我的解决方法是在23:58:45之后使用一个日期,以确保将来没有问题?