Search code examples
iosnsdatensdateformatteruilocalnotificationnstimezone

UILocalNotification - Fire at 6:00am in every time zone


I'm having trouble getting my head around time zones and can't seem to solve it.

The user should enter a time for an alarm to go off. So they choose 6:00am Sunday (using a pickerView) while in Sydney Australia's time zone.

Then when their device changes time zone to Los Angeles, USA, the alarm should still go off at 6:00am in LA's time (which is now 1:00AM or something in Sydney's time).

Setting the notification:

UILocalNotification *localNotification;
[localNotification setTimeZone:[NSTimeZone localTimeZone]];

Reading the notification to display in a TableView:

NSDate *fd = <the firedate of the scheduled notification>
NSDateFormatter* df_local = [[[NSDateFormatter alloc] init] autorelease];
//[df_local setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[df_local setTimeZone:[NSTimeZone localTimeZone]];
[df_local setDateFormat:@"hh:mm"];
NSString* ts_local_string = [df_local stringFromDate:fd];

Using that code I set the time to 6:00am in Sydney, but when viewing it in Los Angeles, the time is now 1:00pm.

What should I set the timezone to when Setting the UILocalNotification, and what I should set the timezone to when reading the Notification, so that the time is 6:00am localtime when viewed in both Sydney and Los Angeles.

Thanks


Solution

  • I think I've manage to figure it out.

    UILocalNotification *localNotification;
    [localNotification setTimeZone:[NSTimeZone localTimeZone]];
        [localNotification setFireDate:fireDate];
    

    This will make whatever Date is in fireDate the time/Date that the notification will go off, in the user's current timezone. So it will go off at 6:00am in Sydney, then again at 6:00am in Los Angeles, etc.

    So that part was working as intended, where I had made the mistake was in displaying the time.

    Instead of the code in my question I needed to set the timeZone of the NSDateFormatter to the timeZone of the UILocalNotification:

    UILocalNotification *myLN = <The UILocalNotification we've retrieved from somewhere>;
    NSDateFormatter* df_local = [[[NSDateFormatter alloc] init] autorelease];
    [df_local setTimeZone:myLN.timeZone];
    [df_local setDateFormat:@"hh:mm"];
    NSString* ts_local_string = [df_local stringFromDate:fd];