Programmatically getting the date “next Sunday at 5PM”

后端 未结 1 693
谎友^
谎友^ 2020-12-06 13:39

Edited 07/08/13: Apple has an excellent set of WWDC videos that really helped me understand the various date and time classes in Objective-C, and how to correctly pe

相关标签:
1条回答
  • 2020-12-06 14:17

    First get the current day of the week:

    NSDate *now = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents *dateComponents = [calendar components:NSCalendarUnitWeekday | NSCalendarUnitHour fromDate:now];
    NSInteger weekday = [dateComponents weekday];
    

    The Apple docs define a weekday as:

    Weekday units are the numbers 1 through n, where n is the number of days in the week. For example, in the Gregorian calendar, n is 7 and Sunday is represented by 1.

    Next figure out how many days to add to get to the next sunday at 5:

    NSDate *nextSunday = nil;
    if (weekday == 1 && [dateComponents hour] < 5) {
        // The next Sunday is today
        nextSunday = now;
    } else {
        NSInteger daysTillNextSunday = 8 - weekday;
        int secondsInDay = 86400; // 24 * 60 * 60  
        nextSunday = [now dateByAddingTimeInterval:secondsInDay * daysTillNextSunday];
     }
    

    To get it at 5:00 you can just change the hour and minute on nextSunday to 5:00. Take a look at get current date from [NSDate date] but set the time to 10:00 am

    0 讨论(0)
提交回复
热议问题