当我试图让当前的星期日期显示在日志中时(星期一到星期日),这就像一周从星期日开始。 例如: 本周是38岁。 昨天是九月二十日。我的代码确实显示了周一到周日的日期。 但是今天(9月21日)我的日志显示下周的日期(第39周),当时它仍然是第38周。
我的代码:
NSDate *currentDate = [NSDate date];
NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *currentComps = [myCalendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekOfYearCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:currentDate];
int thisWeeksNumber = currentComps.weekOfYear;
NSLog(@"1 %d", thisWeeksNumber);
[currentComps setWeekday:2];
NSDate *firstDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
NSDate *secondDayOfTheWeek = [self dateByAddingDays:1 toDate:firstDayOfTheWeek];
NSDate *thirdDayOfTheWeek = [self dateByAddingDays:2 toDate:firstDayOfTheWeek];
NSDate *fourthDayOfTheWeek = [self dateByAddingDays:3 toDate:firstDayOfTheWeek];
NSDate *fifthDayOfTheWeek = [self dateByAddingDays:4 toDate:firstDayOfTheWeek];
NSDate *sixthDayOfTheWeek = [self dateByAddingDays:5 toDate:firstDayOfTheWeek];
NSDate *seventhDayOfTheWeek = [self dateByAddingDays:6 toDate:firstDayOfTheWeek];
NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
myDateFormatter.dateFormat = @"yyyy-MM-dd";
NSString *firstStr = [myDateFormatter stringFromDate:firstDayOfTheWeek];
NSString *secondStr = [myDateFormatter stringFromDate:secondDayOfTheWeek];
NSString *thirdStr = [myDateFormatter stringFromDate:thirdDayOfTheWeek];
NSString *fourthStr = [myDateFormatter stringFromDate:fourthDayOfTheWeek];
NSString *fifthStr = [myDateFormatter stringFromDate:fifthDayOfTheWeek];
NSString *sixthStr = [myDateFormatter stringFromDate:sixthDayOfTheWeek];
NSString *seventhStr = [myDateFormatter stringFromDate:seventhDayOfTheWeek];
NSLog(@"\n %@ \n %@ \n %@ \n %@ \n %@ \n %@ \n %@", firstStr, secondStr, thirdStr, fourthStr, fifthStr, sixthStr, seventhStr);
}
我的NSDate方法:
- (NSDate*)dateByAddingDays:(NSInteger)days toDate:(NSDate *)date
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.day = days;
return [calendar dateByAddingComponents: comps toDate: date options: 0];
}
这应该显示所有日子的第38周,但它显示下周的日期,因为它是星期天。 (因为我写的是第38周,也就是9月21日)