Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically getting the date "next Sunday at 5PM"

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 perform time calculations/manipulations with them.

"Solutions to Common Date and Time Challenges" (HD video, SD video, slides (PDF)) (WWDC 2013)
"Performing Calendar Calculations" (SD video, slides (PDF)) (WWDC 2011)

Note: links require a free Apple Developer membership.

I'm writing an app for a friend's podcast. She broadcasts her show live every Sunday at 5PM, and I would like to write some code in my app to optionally schedule a local notification for that time, so that the user is reminded of when the next live show is. How would I go about getting an NSDate object that represents "the next Sunday, at 5 PM Pacific time." (obviously this would have to be converted into whatever timezone the user is using)

like image 517
Donald Burr Avatar asked Oct 10 '12 22:10

Donald Burr


1 Answers

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

like image 59
Nathan Villaescusa Avatar answered Oct 10 '22 07:10

Nathan Villaescusa