2017-12-18 25 views

回答

1

您可以使用下面的代碼獲得這個星期和下個星期的所有日期: -

NSArray * allDatesOfThisWeek = [self daysThisWeek]; 
NSArray * allDatesOfNextWeek = [self daysNextWeek]; 

以下方法用於計算該周的日期: -

-(NSArray*)daysThisWeek 
{ 
    return [self daysInWeek:0 fromDate:[NSDate date]]; 
} 

-(NSArray*)daysNextWeek 
{ 
    return [self daysInWeek:1 fromDate:[NSDate date]]; 
} 
-(NSArray*)daysInWeek:(int)weekOffset fromDate:(NSDate*)date 
{ 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 

    //ask for current week 
    NSDateComponents *comps = [[NSDateComponents alloc] init]; 
    comps=[calendar components:NSWeekCalendarUnit|NSYearCalendarUnit fromDate:date]; 
    //create date on week start 
    NSDate* weekstart=[calendar dateFromComponents:comps]; 

    NSDateComponents* moveWeeks=[[NSDateComponents alloc] init]; 
    moveWeeks.weekOfYear=weekOffset;    
    weekstart=[calendar dateByAddingComponents:moveWeeks toDate:weekstart options:0]; 


    //add 7 days 
    NSMutableArray* week=[NSMutableArray arrayWithCapacity:7]; 
    for (int i=1; i<=7; i++) { 
     NSDateComponents *compsToAdd = [[NSDateComponents alloc] init]; 
     compsToAdd.day=i; 
     NSDate *nextDate = [calendar dateByAddingComponents:compsToAdd toDate:weekstart options:0]; 
     [week addObject:nextDate]; 

    } 
    return [NSArray arrayWithArray:week]; 
} 

如果你想從今天獲得下週的日期,然後通過weekOffset = 2像這樣: -

NSArray * allDatesOfNextToNextWeek = [self daysInWeek:2 fromDate:now]; 

如果你希望從今天獲得前一週的日期,然後通過weekOffset = -1是這樣的: -

NSArray * allDatesOfPreviousWeek = [self daysInWeek:-1 fromDate:now]; 

希望,這是你在找什麼。任何擔心都會回到我身上。

0

NSCalendar包含專用的方法來做到這一點,例如nextDateAfterDate:matchingUnit:value:options:dateByAddingComponents:toDate:options:

// Get the current calendar 
NSCalendar *calendar = [NSCalendar currentCalendar]; 
// Get the next occurrence for the first weekday of the current calendar 
NSDate *startOfNextWeek = [calendar nextDateAfterDate:[NSDate date] matchingUnit:NSCalendarUnitWeekday value:calendar.firstWeekday options:NSCalendarMatchStrictly]; 
// Create new date components +7 days and -1 seconds 
NSDateComponents *endOfNextWeekComponents = [[NSDateComponents alloc] init]; 
endOfNextWeekComponents.day = 7; 
endOfNextWeekComponents.second = -1; 
// Add the date components to the start date to get the end date. 
NSDate *endOfNextWeek = [calendar dateByAddingComponents:endOfNextWeekComponents toDate:startOfNextWeek options:NSCalendarMatchStrictly]; 

NSLog(@"%@ - %@", startOfNextWeek, endOfNextWeek); 
相關問題