NSCalendar dateFromComponents: GMT timezone instead of systemTimeZone

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 the console:

 Europe/Moscow (MSKS) offset 14400 (Daylight) Europe/Moscow (MSKS) offset 14400 (Daylight) 2011-08-31 20:00:00 +0000 

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

What do I need to fix the correct time zone?

+5
ios iphone nscalendar nstimezone
Sep 06 2018-11-11T00:
source share
2 answers

The output you see is perfectly normal. If you are NSLog a NSDate directly, you will get everything that the description method returns, which is a date representation in GMT format (but it is not cut from the stone).

The objects

NSDate does not depend on time zones. A NSDate is an absolute point in time measured from a NSDate date. For example, at the time of writing the current date, this is something like 337035053.199801 (seconds after the 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 correct time zone? You need to use NSDateFormatter to get a string representation of your NSDate in any time zone you like.

+6
Sep 06 2018-11-11T00:
source share

This question arises quite often, and the answer is to use NSDateFormatter to get the desired result for the date format. Currently, it is always printed with GMT time zone. Here is a discussion of the documentation for NSDate :

Discussion
Representation is not guaranteed constant across versions of the operating system. To format a date, you should use the date formatting object instead (see NSDateFormatter and the Data Formatting Guide)

+1
Sep 06 2018-11-11T00:
source share



All Articles