5

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)

Donald Burr
  • 2,281
  • 2
  • 23
  • 31

1 Answers1

14

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

Omar
  • 105
  • 4
Nathan Villaescusa
  • 17,331
  • 4
  • 53
  • 56
  • There's a subtle bug in this code. The `calendar` implicitly uses the current locale. If that means for example a New Zealand time zone it differs substantially differs from Pacific time. The result might be that the code calculates the next Sunday in 6 or 7 days when the next *Californian* Sunday-at-5 is only a couple of hours ahead. – Nikolai Ruhe Jul 08 '13 at 23:36
  • 2
    Also, the code to calculate `nextSunday` breaks when there's a daylight change in that period. – Nikolai Ruhe Jul 08 '13 at 23:38