Search code examples
iosobjective-cnsdatenscalendarnstimezone

Significant time change in Different time zone


I am working with two or three different time zones in my iOS app. I want to get the midnight time change notification/callback in all the respective time zones. I guess i can only use the UIApplicationSignificantTimeChangeNotification for the time change in my current timezone. But i want to get it for all the different timezones i am using for example America/Los_Angeles and Europe/Berlin.

I am currently trying to get the current time in the specific time zone and then add some type of timer for the difference of each timezone with its 12 at night and then use that callback to do whatever i want to do.

Can some body suggest some more elegant solution about this or is there any apple APi that provide such feature or close to this feature?

Any help for this.


Solution

  • I figured it out using the following Code

    NSDate *gmtDate = [NSDate date];
    NSInteger secondsFromGMT = [[NSTimeZone timeZoneWithName:self.timeZoneID] secondsFromGMT];
    NSCalendar *cal = [NSCalendar currentCalendar];
    [cal setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [cal setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    NSDateComponents *components =  [cal components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour |
                                                     NSCalendarUnitMinute | NSCalendarUnitSecond)  fromDate:gmtDate];
    NSInteger hours = 24 - (components.hour + 1);
    NSInteger mins = 60 - (components.minute + 1);
    NSInteger seconds = 60 - components.second;
    
    // Here we are getting seconds to GMT MidNight
    NSInteger secondsToMidNight = convertHourMinSecToSeconds(hours ,mins,seconds);
    
    NSArray *array = convertSecondToHourMinSec(secondsToMidNight - secondsFromGMT);
    hours = [array[0] integerValue] % 24;
    mins = [array[1] integerValue] % 60;
    seconds = [array[2] integerValue] % 60;
    
    // Here we are getting seconds to desired city midnight
    secondsToMidNight = convertHourMinSecToSeconds(hours, mins,seconds);
    

    convertHourMinSecToSeconds & convertSecondToHourMinSec is my own function and their body is very simple as the name is self explanatory.