我遇到了一些問題。我希望我在本週顯示所有日期(因爲我寫的是第38周(格里高利))。我擁有的不錯,但它並沒有顯示正確的日子。例如: 本週星期一是9月15日,星期日是9月21日。 當我設置一週的第一天時,它將它設置爲9月14日星期天。顯示當前工作日和日期
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); //This displays the correct week.
[currentComps setWeekday:1];
NSDate *firstDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
[currentComps setWeekday:2];
NSDate *secondDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
[currentComps setWeekday:3];
NSDate *thirdDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
[currentComps setWeekday:4];
NSDate *fourthDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
[currentComps setWeekday:5];
NSDate *fifthDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
[currentComps setWeekday:6];
NSDate *sixthDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
[currentComps setWeekday:7];
NSDate *seventhDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
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);
這應該顯示九月15日至九月21,但它顯示九月14日(星期日)至九月21日(星期六)。
在此先感謝!
是的,我已經試過了。但是,我如何獲得9月21日的星期天? Cuz'一週不會以星期天開始。 – Dridia 2014-09-20 16:18:44
@Dridia:檢查更新的答案。 – sha 2014-09-20 16:32:10
我不知道我應該如何在我的代碼中實現這一點。 – Dridia 2014-09-20 16:35:57