Current Week Start and End Date

后端 未结 16 1384
轮回少年
轮回少年 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:10

    Here's some code and it also checks an edge case where the beginning of the week starts in the prior month. You can get end of week by setting setWeekday to 7 and you can get the prior week by subtracting 1 from [components week]

    // Finds the date for the first day of the week
    - (NSDate *)getFirstDayOfTheWeekFromDate:(NSDate *)givenDate
    {
        NSCalendar *calendar = [NSCalendar currentCalendar];
    
        // Edge case where beginning of week starts in the prior month
        NSDateComponents *edgeCase = [[NSDateComponents alloc] init];
        [edgeCase setMonth:2];
        [edgeCase setDay:1];
        [edgeCase setYear:2013];
        NSDate *edgeCaseDate = [calendar dateFromComponents:edgeCase];
    
        NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:edgeCaseDate];
        [components setWeekday:1]; // 1 == Sunday, 7 == Saturday
        [components setWeek:[components week]];
    
        NSLog(@"Edge case date is %@ and beginning of that week is %@", edgeCaseDate , [calendar dateFromComponents:components]);
    
        // Find Sunday for the given date
        components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:givenDate];
        [components setWeekday:1]; // 1 == Sunday, 7 == Saturday
        [components setWeek:[components week]];
    
        NSLog(@"Original date is %@ and beginning of week is %@", givenDate , [calendar dateFromComponents:components]);
    
        return [calendar dateFromComponents:components];
    }
    

提交回复
热议问题