6

这段代码

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]返回的 NSDate 值带有错误的时区 (GMT)。

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

4

2 回答 2

6

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

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

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

于 2011-09-06T21:08:54.137 回答
1

这个问题经常出现,答案是使用 anNSDateFormatter来获得所需的日期格式输出。目前,它始终使用 GMT 时区打印。以下是对文档的讨论NSDate

讨论
不保证表示在操作系统的不同版本中保持不变。要格式化日期,您应该使用日期格式化程序对象(请参阅 NSDateFormatter 和数据格式化指南)

于 2011-09-06T21:09:24.060 回答