【问题标题】:Significant time change in Different time zone不同时区的显着时间变化
【发布时间】:2014-09-25 08:45:37
【问题描述】:

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

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

有人可以提出一些更优雅的解决方案吗?或者是否有任何苹果 API 提供此类功能或接近此功能?

对此有任何帮助。

【问题讨论】:

  • 是的,只需设置本地通知。 IIRC,您甚至可以指定要使用的时区,这样您就不必自己进行任何时间算术。

标签: ios objective-c nsdate nscalendar nstimezone


【解决方案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 是我自己的函数,它们的主体很简单,因为名称是不言自明的。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2010-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-09
      • 2012-07-22
      • 2019-12-19
      • 1970-01-01
      相关资源
      最近更新 更多