NSCalendar dateFromComponents: GMT timezone instead of systemTimeZone

纵然是瞬间 提交于 2019-12-19 07:38:09

问题


This code

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]);

shows the following in console:

Europe/Moscow (MSKS) offset 14400 (Daylight)

Europe/Moscow (MSKS) offset 14400 (Daylight)

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

So, the timezone for calendar and components is specified correctly, but [gregorian dateFromComponents:comp] returns NSDate value with wrong time zone (GMT).

What do I need to correct to get proper timezone?


回答1:


The output you are seeing is perfectly normal. If you NSLog a NSDate object directly, you will get whatever the description method returns, which is the GMT representation of the date (but that is not carved in stone).

NSDate objects are not subject to timezones. A NSDate represents an absolute instant in time measured from a reference date. For example, at the time of writing, the current date is something like 337035053.199801 (seconds since reference date), which can be represented as 2011-09-06 20:50:53 GMT or 2011-09-06 22:50:53 CEST. Both are different human readable representations of the same date.

In conclusion, what do you need to get the proper timezone? You need to use NSDateFormatter to get a string representation of your NSDate in any timezone you like.




回答2:


This question comes up quite often and the answer is to use an NSDateFormatter to get the desired output for the date format. Currently it is always printed with the GMT timezone. Here is the discussion for the documentation for NSDate:

Discussion
The representation is not guaranteed to remain constant across different releases of the operating system. To format a date, you should use a date formatter object instead (see NSDateFormatter and Data Formatting Guide)



来源:https://stackoverflow.com/questions/7325837/nscalendar-datefromcomponents-gmt-timezone-instead-of-systemtimezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!