ios - 从 NSDate 获取小时组件

标签 ios iphone objective-c nsdatecomponents nstimezone

我正在尝试从 NSDate 获取小时组件。 这是我所做的:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+1"]];
    NSDateComponents *startComponents = [calendar components:DATE_COMPONENTS fromDate:_start];
    startComponents.timeZone =  [NSTimeZone timeZoneWithName:@"GMT+1"];
    int hours = [startComponents hour];

在昨天之前,小时值始终提前一小时。但从昨天开始,小时值提前了 2 小时。

我知道这与 NSTimezoneDST 有关。但我无法集中精力!

有人可以帮我吗?

最佳答案

"GMT+1" 不被识别为时区名称,因此

[NSTimeZone timeZoneWithName:@"GMT+1"]

nil 并且使用本地时区,这可能是您所在国家/地区上周末从冬令时 (GMT+01) 切换到夏令时 (GMT+02) .

"GMT+1" 替换为 "GMT+01":

[NSTimeZone timeZoneWithName:@"GMT+01"]
// or alternatively:
[NSTimeZone timeZoneForSecondsFromGMT:3600]

工作并给出预期的结果。

请注意,设置NSCalendar 的时区就足够了。设置时区 NSDateComponents 在这种情况下无效。

关于ios - 从 NSDate 获取小时组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22765042/

相关文章:

ios - Collection View 第一个单元格大小问题

iphone - 如何在从 Apple 获取应用程序 ID 之前测试 iOS Facebook 应用程序?

ios - UITextField 的 NSLayoutConstraints - 错误

objective-c - NSUserDefaults 与 sqlite3

ios - cell.accessoryType = .Checkmark

ipad - 我需要Mac OS X 10.6才能为iPad开发吗?

ios - 带有按钮 addTarget 事件的标签不会触发

ios - 如何在 objective-c 中用破折号替换空格?

iphone - 在 iPhone 调试器中将鼠标悬停在变量名称上时出现问题

ios - UIApperance 和各种崩溃