iphone - NSCalendar dateFromComponents : GMT timezone instead of systemTimeZone

标签 iphone ios nscalendar nstimezone

这段代码

NSCalendar *calendar =[NSCalendar currentCalendar];
[gregorian setTimeZone:tz];

NSLog(@"%@", [gregorian timeZone]);

NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:[NSDate date]];

[comp setDay:info.day];
[comp setMonth:info.month];
[comp setYear:info.year];
[comp setHour:info.hour];
[comp setMinute:info.minute];
[comp setSecond:info.second];
[comp setTimeZone:tz];  

NSLog(@"%@", [comp timeZone]);
NSLog(@"%@", [gregorian dateFromComponents:comp]);

在控制台中显示以下内容:

Europe/Moscow (MSKS) offset 14400 (Daylight)

Europe/Moscow (MSKS) offset 14400 (Daylight)

2011-08-31 20:00:00 +0000

因此,日历和组件的时区指定正确,但 [gregorian dateFromComponents:comp] 返回时区 (GMT) 错误的 NSDate 值。

我需要更正什么以获得正确的时区?

最佳答案

您看到的输出是完全正常的。如果您直接 NSLog 一个 NSDate 对象,您将得到 description 方法返回的任何内容,这是日期的 GMT 表示(但这不是一成不变的)。

NSDate 对象不受时区限制。 NSDate 表示从引用日期开始测量的绝对 时间。例如,在撰写本文时,当前日期类似于 337035053.199801(自引用日期以来的秒数),可以表示为 2011-09-06 20:50:53 GMT2011-09-06 22:50:53 CEST。两者都是相同日期的不同人类可读表示。

总而言之,您需要什么才能获得正确的时区?您需要使用 NSDateFormatter 来获取您喜欢的任何时区的 NSDate 的字符串表示形式。

关于iphone - NSCalendar dateFromComponents : GMT timezone instead of systemTimeZone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7325837/

相关文章:

iPhone 企业应用程序分发 - 需要互联网连接吗?

iphone - UIpickerView 在同一个 ScrollView 中填充多个 uitextFields

iphone - 应用内购买项目的促销代码

iphone - Youtube API 认证 - Iphone

ios - uiview touch move 获取uiview上的 anchor

iphone - 获取照片 Assets 库 Assets 表示大小为零

ios - 如何从两个 UILabels 之一随机返回文本?

ios - 使用 setDoesRelativeDateFormatting : YES and setDateFormat: with NSDateFormatter

ios - 我如何解决 ios8 的日期问题

ios - 为什么 `ordinality(of: .day, in: .era, for: date)` 对不同时区的 2 个日期给出相同的结果?