dynamically create date for previous sunday at 12:00 AM

前端 未结 4 960
鱼传尺愫
鱼传尺愫 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:28

    No need to manually calculate seconds (which is dangerous anyway because of daylight saving etc.). The following should do exactly what you want:

    NSDate *today = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [calendar setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"]]; // force US locale, because other countries (e.g. the rest of the world) might use different weekday numbering
    
    NSDateComponents *nowComponents = [calendar components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];
    
    [nowComponents setWeekday:1]; //Sunday
    [nowComponents setHour:0]; // 12:00 AM = midnight (12:00 PM would be 12)
    [nowComponents setMinute:0];
    [nowComponents setSecond:0];
    
    NSDate *previousSunday = [calendar dateFromComponents:nowComponents];
    

提交回复
热议问题