ios - 夏令时在 iOS 中生效时出现 Timezoneoffset 错误

标签 ios ios5 ios4

friend 们,我正在根据下面的计算得到一个日期

      NSCalendar *gregorian          = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

        NSDate *expectedDate           = [gregorian dateByAddingComponents:components toDate:startDate options:0];
        NSTimeInterval timeZoneOffset  = -[[NSTimeZone systemTimeZone] secondsFromGMTForDate:expectedDate];
        NSDate *localDate              = [expectedDate dateByAddingTimeInterval:(timeZoneOffset)];

         NSString *date  = [dateFormatter stringFromDate:localDate];

但是当夏令时生效时日期出错,并且当夏令时生效时timeZoneOffset也发生变化,但是无论夏令时是否生效我都想要相同的日期不..

请问 friend 们,我该如何处理,请帮忙。

问候 兰 git

最佳答案

您不需要自己处理夏令时,“dateFormatter”会自动为您完成。通常你只需要一个 UTC (GMT+0) 时间的 NSDate 对象,“dateFormatter”也有一个时区,将在它自己的时区显示那个时间。

NSCalendar 和 NSDateFormatter 有时区设置。 NSDate 只是相对于 GMT+0 的一个时间点。

例子: “expectedDate”是 1 月 1 日凌晨 4 点(GMT+0) "dateFormatter"设置了时区 GMT+2(例如 Europe/Berlin),那么在将 "expectedDate"转换为字符串时,由于其自​​身的时区,将输出 "January 1st 6am"。

所以基本上您只需要确保“startDate”是正确的并且“gregorian”和“dateFormatter”使用正确的时区。默认情况下,他们使用系统时区,这似乎是您想要使用的时间。所以你只需要这些行(并且 startDate 必须是正确的):

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *expectedDate = [gregorian dateByAddingComponents:components toDate:startDate options:0];
    NSString *date  = [dateFormatter stringFromDate:expectedDate];

如果这不起作用,请发布更多有关如何生成 startDate 和 dateFormatter 的代码。

关于ios - 夏令时在 iOS 中生效时出现 Timezoneoffset 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9819509/

相关文章:

ios - 包含数组对象的字典在将其传递给 WatchKit 扩展时崩溃

ios - CSS min-height 在 webkit 上不起作用

ios - 为什么 watchOS2 上的 openSystemURL 打不开电话 : urls

ios - XCode 4.4 iOS 5.1 模拟器问题

gcc - 内部编译器错误 : Bus error with LLVM GCC 4. 2 编译器

ios - 重用 Storyboard segue 中涉及的细节 UIViewController

iphone - 首次使用前 UISearchBar 大小不一致?

ios - 在 iOS 中查找 Facebook 匹配帖子

iphone - 替换核心数据模型,无需迁移

objective-c - iOS 4 - 使用 block 作为类的成员