Programmatically getting the date “next Sunday at 5PM”

对着背影说爱祢 提交于 2019-11-28 00:16:00
Nathan Villaescusa

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!