• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 如何获取相对于 GMT 以外的时区的 NSCalendarComponent 值?

[复制链接]
菜鸟教程小白 发表于 2022-12-12 10:37:48 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

为什么以下标记的断言会失败?我只是在中欧的一台主机上运行这个单元测试。因此 NSCalendar.currentCalendar.timeZone 是 CEST,即 GMT+0200。 NSDateComponents 返回此时区,但其其他值(例如年份等)显然与 GMT 相关。如何获取与 CEST 相关的值?

- (void)test {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mmZZZ";
    dateFormatter.timeZone   = [NSTimeZone timeZoneWithAbbreviation"CEST"];
    XCTAssertEqual(2 * 60 * 60, dateFormatter.timeZone.secondsFromGMT, @"");

    NSDate *time = [dateFormatter dateFromString"2014-01-01T00:00+0200"]; // midnight on a Wednesday

    NSCalendar *calendar = NSCalendar.currentCalendar; // i.e. CEST
    XCTAssertEqual(2 * 60 * 60, calendar.timeZone.secondsFromGMT, @"");

    NSDateComponents *components = [calendar components: NSYearCalendarUnit |
                                                         NSMonthCalendarUnit |
                                                         NSDayCalendarUnit |
                                                         NSWeekdayCalendarUnit |
                                                         NSHourCalendarUnit |
                                                         NSMinuteCalendarUnit |
                                                         NSTimeZoneCalendarUnit
                                               fromDate:time];

    XCTAssertEqual(components.year, 2014, @""); // fails with 2013
    XCTAssertEqual(components.month, 1, @""); // fails with 12
    XCTAssertEqual(components.day, 1, @""); // fails with 31
    XCTAssertEqual(components.weekday, 4, @""); // fails with 3 (Tuesday)
    XCTAssertEqual(components.hour, 0, @""); // fails with 23
    XCTAssertEqual(components.minute, 0, @""); // succeeds
    XCTAssertEqual(components.timeZone.secondsFromGMT, 2 * 60 * 60, @""); // succeeds (CEST)
}



Best Answer-推荐答案


NSCalendar.currentCalendar.timeZone 现在是 CEST 或 GMT+02,因为夏令时现在在您所在的时区有效。但是在 2014-01-01,夏令时没有激活。因此,该日期的所有转换都使用 GMT+01 偏移量完成。

这就是你的情况:

  • 字符串“2014-01-01T00:00+0200”被转换为NSDate“2013-12-31 22:00:00 +0000”,因为您明确指定输入字符串中的 GMT 偏移量“+0200”。 因此,将 dateFormatter.timeZone 设置为“CEST”无效。

  • NSDate "2013-12-31 22:00:00+0000"被转换为日期组件,使用您的 当前日历。由于 该日期 的 GMT 偏移量是“GMT+0100”,因此您会得到 对应“2013-12-31 23:00:00+0100”的日期组件。

如果你用

进行计算
NSDate *time = [dateFormatter dateFromString"2014-01-01T00:00+0100"];

那么测试成功。

关于ios - 如何获取相对于 GMT 以外的时区的 NSCalendarComponent 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24464843/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap