How to get next week start and end date in Objective-c?

时间:2017-12-18 04:52:53

标签: objective-c

I have try to get next week start and end date but I have got current week start and end date.How can get next week start and end date in Objective-c.

2 个答案:

答案 0 :(得分:0)

You can get all dates of this week and next week using following code:-

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

Following methods are used for calculating dates of this week:-

-(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];
}

If you want to get dates of next to next week from today, then pass weekOffset=2 like this:-

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

If you want to get dates of previous week from today, then pass weekOffset=-1 like this:-

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

Hope, this is what you're looking for. Any concern get back to me.

答案 1 :(得分:0)

Update-Database contains dedicated methods to do that for example NSCalendar and nextDateAfterDate:matchingUnit:value:options:

dateByAddingComponents:toDate:options: