2014-09-21 90 views
2

當我嘗試使當前週數顯示在日誌中(週一至週日)時,它就像一週開始於週日。 例如: 這個星期是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日)的

+0

[myCalendar setFirstWeekday:1] ; – danh 2014-09-21 16:53:36

+0

我將它添加到我的代碼中,但沒有發生任何事情。有任何其他想法? – Dridia 2014-09-21 17:02:17

+0

@danh星期一是2. – 2014-09-21 17:37:20

回答

7

你需要調用setFirstWeekday:2一個NSUInteger參數值(星期日是1

[myCalendar setFirstWeekday:2]; 
+0

幹得好。我對這篇文章的標題感到困惑。 (應該閱讀,如何讓星期一開始,而不是星期天)。 – danh 2014-09-21 17:41:52

+0

週日它也是en-US文化的默認設置。 (我不是100%確定本地化應用於NSCalendar的時間) – 2014-09-21 17:43:19

+0

事情是我顯示下週的日子,而不是本週(因爲它是星期日,昨天它就像一個魅力!) – Dridia 2014-09-21 18:09:40

相關問題