不同时区的重大时间变化

时间:2014-09-25 08:45:37

标签: ios objective-c nsdate nscalendar nstimezone

我在iOS应用中使用两个或三个不同的时区。我希望在所有相应的时区中获得午夜时间变化notification/callback。我想我只能使用UIApplicationSignificantTimeChangeNotification来改变我当前时区的时间。但我想为我使用的所有不同时区获取它,例如America/Los_AngelesEurope/Berlin

我目前正在尝试获取特定时区的当前时间,然后为每个时区的差异添加某种类型的计时器,其中它在晚上12,然后使用该回调来做我想做的任何事情。

有些机构可以提出一些更优雅的解决方案,或者有没有提供此类功能或接近此功能的苹果APi?

对此有任何帮助。

2 个答案:

答案 0 :(得分:1)

我使用以下代码

计算出来
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是我自己的功能,他们的身体非常简单,因为名称是自我解释的。

答案 1 :(得分:0)

我建议使用UILocalNotification。将fireDate设置为不同时区的午夜,并将时区的名称放在userInfo中。在iOS 8中,NSCalendar上有一些新方法可以帮助您获得正确的开火日期。

应用代表收到本地通知。当你得到一个,你可以发出自己的内部通知来指示时间的变化。