Current Week Start and End Date

后端 未结 16 1356
轮回少年
轮回少年 2020-11-30 01:56

I want to get the current week start and end date and I also want to use the previous week start and end date and next week of the start and end date in current month.

16条回答
  •  春和景丽
    2020-11-30 02:35

    By take advantage of the method rangeOfUnit:startDate:interval:forDate: of NSDate, there is a simpler way to achieve this:

    - (void)startDate:(NSDate **)start andEndDate:(NSDate **)end ofWeekOn:(NSDate *)date{
        NSDate *startDate = nil;
        NSTimeInterval duration = 0;
        BOOL b = [[NSCalendar currentCalendar] rangeOfUnit:NSWeekCalendarUnit startDate:&startDate interval:&duration forDate:date];
        if(! b){
            *start = nil;
            *end = nil;
            return;
        }
        NSDate *endDate = [startDate dateByAddingTimeInterval:duration-1];
        *start = startDate;
        *end = endDate;
    }
    
    NSDate *this_start = nil, *this_end = nil;
    [self startDate:&this_start andEndDate:&this_end ofWeekOn:[NSDate date]];
    

    So now you have the start date and end date of this week. Then last week:

    NSDate *lastWeekDate = [this_start dateByAddingTimeInterval:-10];
    NSDate *last_start = nil, *last_end = nil;
    [self startDate:&last_start andEndDate:&last_end ofWeekOn:lastWeekDate];
    

    Next week:

    NSDate *nextWeekDate = [this_end dateByAddingTimeInterval:10];
    NSDate *next_start = nil, *next_end = nil;
    [self startDate:&next_start andEndDate:&next_end ofWeekOn:nextWeekDate];
    

    Now you have them all.

提交回复
热议问题