我正在使用 Objective-C 创建一堆代码来确定从 1/1/1901 到 31/12/2000 每月的第一天。我想得到这个输出:
1/1/1901
1/2/1901
1/3/1901
.
.
.
1/11/2000
1/12/2000
但我得到每个月的最后一天:
31/1/1901
28/2/1901
.
.
.
30/11/2000
31/12/2000
这是我的代码:
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy"];
NSDate *date = [[NSDate alloc] init];
date = [formatter dateFromString:@"01/01/1901"];
NSDate *stopDate = [[NSDate alloc] init];
stopDate = [formatter dateFromString:@"31/12/2000"];
NSCalendar *cal = [NSCalendar currentCalendar];
while ([[date earlierDate:stopDate] isEqualToDate:date]){
NSDateComponents *comps = [cal components:NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:date];
if ([comps month] == 12){
[comps setMonth:1];
[comps setYear:[comps year]+1];
}else{
[comps setMonth:[comps month]+1];
}
date = [cal dateFromComponents:comps];
NSLog(@"%@",date);
}
}
return 0;
}
我哪里错了?