當我嘗試使當前週數顯示在日誌中(週一至週日)時,它就像一週開始於週日。 例如: 這個星期是38. 昨天是9月20日。我的代碼確實顯示星期一到星期天的日子是正確的。 但今天(九月21)我的日誌顯示未來幾週日(39周)時,它仍然是38周如何使NSCalendar周從週一而不是週日開始
我的代碼:
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日)的
[myCalendar setFirstWeekday:1] ; – danh 2014-09-21 16:53:36
我將它添加到我的代碼中,但沒有發生任何事情。有任何其他想法? – Dridia 2014-09-21 17:02:17
@danh星期一是2. – 2014-09-21 17:37:20