dynamically create date for previous sunday at 12:00 AM

前端 未结 4 961
鱼传尺愫
鱼传尺愫 2021-01-14 16:13

I\'m struggling to figure out how to dynamically create a date object for the most previous sunday at 12:00 AM

I was thinking I could get today\'s date and then subt

4条回答
  •  伪装坚强ぢ
    2021-01-14 16:21

    I'll leave worrying about transitions between daylight savings time to you:

    NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDate *date = [NSDate date];
    NSLog(@"date %@", date);
    
    NSDateComponents *componentsToday = [gregorian components:NSWeekdayCalendarUnit fromDate:date]; // NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | 
    NSInteger days = componentsToday.weekday - 1;
    NSLog(@"Days=%d", days);
    
    NSDate *lastSunday = [date dateByAddingTimeInterval:-days*60*60*24];
    NSLog(@"lastSunday %@", lastSunday);
    
    NSDateComponents *componentsSunday = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit  fromDate:lastSunday];
    [componentsSunday setHour:0];
    [componentsSunday setMinute:0];
    [componentsSunday setSecond:0];
    NSDate *targetDate = [gregorian dateFromComponents:componentsSunday];
    NSLog(@"TargetDate %@", targetDate);
    

提交回复
热议问题