iOS 10中Calendar.current.timeZone未返回本地时区的问题咨询
iOS 10中
Calendar.current.timeZone返回GMT的问题解答 首先明确:这确实是iOS 10系统的一个已知bug,苹果在iOS 11版本中修复了这个问题,让Calendar.current.timeZone可以正确返回本地时区。
针对这个问题,有几个可靠的解决方法:
直接使用
TimeZone.current替代:如果你的需求只是获取本地时区,不需要和Calendar实例绑定,直接调用TimeZone.current(Objective-C中对应[NSTimeZone localTimeZone])就能得到正确的本地时区,这个接口在iOS 10及以上都是正常工作的。手动配置Calendar的时区:如果业务逻辑必须使用Calendar实例,可以创建一个
Calendar.current的副本,手动为它设置正确的时区,代码示例如下:
Swift版本:
// 创建当前日历的副本 var fixedCalendar = Calendar.current // 手动设置为本地时区 fixedCalendar.timeZone = TimeZone.current // 后续使用这个fixedCalendar实例即可
Objective-C版本:
NSCalendar *fixedCalendar = [NSCalendar currentCalendar]; [fixedCalendar setTimeZone:[NSTimeZone localTimeZone]];
- 使用自动更新的时区(可选):如果需要时区跟随系统设置自动更新,可以用
TimeZone.autoupdatingCurrent替代TimeZone.current,这样当用户修改系统时区时,你的Calendar实例的时区也会自动同步:
var fixedCalendar = Calendar.current fixedCalendar.timeZone = TimeZone.autoupdatingCurrent
这些方法都能完美规避iOS 10的这个时区bug,确保在不同系统版本下都能获取到正确的本地时区。
内容的提问来源于stack exchange,提问作者shoujs
相关产品推荐
相关产品推荐

