Current Week Start and End Date

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

    rangeOfUnit:startDate:interval:forDate:. It gives you the start and the interval for a certain time unit. With it it is easy to find the start of the week in the used calendar and add the range-1 to get the latest second in that week.

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDate *now = [NSDate date];
    NSDate *startOfTheWeek;
    NSDate *endOfWeek;
    NSTimeInterval interval;
    [cal rangeOfUnit:NSWeekCalendarUnit 
           startDate:&startOfTheWeek 
            interval:&interval 
             forDate:now];
    //startOfWeek holds now the first day of the week, according to locale (monday vs. sunday)
    
    endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval-1];
    // holds 23:59:59 of last day in week.
    

提交回复
热议问题