2
votes

I have the following date: month = December, day = 01, year = 2011. The date is given as an NSString with the following format "111201" (YYMMdd). Now I want to parse this string into a NSDate object with a NSDateFormatter:

self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateFormat:@"YYMMdd"];
NSDate* date = [self.dateFormatter dateFromString:strDate];

And the output of "111201" is "2011-11-30 23:00:00 +0000". That doesn't make sense to me.

How is this possible? I'd expect "2011-12-01 23:00:00 +0000".

2
It looks like you are reading in a date without time information, so it's assuming a certain base time and then applying a timezone offset. What timezone is your local time set to?Tim Dean
timezone difference does not lead to a difference of a month.Saurabh Passolia
@samfisher - the difference between the two dates is only a day at the most, this is quite probably a timeline issue.jrturton
@samfisher the difference is 1 hour. The OP is probably at GMT+1.Firoze Lafeer
Yes that's right. I'm GMT+1 since I'm in Europe/Berlin.toom

2 Answers

3
votes

When you display NSDate objects in the debugger or output their values via NSLog they are always shown as GMT dates and times (that's what the +0000 at the end means).

Your local time zone appears to be '+0100' (Western Europe?) so the date formatter is operating on 'December 01 2011 00:00am +0100' and creating an NSDate correctly. But at the point of display the NSDate (which is just a single point in time with no timezone information) is shown in GMT - and the equivalent is one hour earlier i.e. 'November 30 2011 23:00pm +0000'.

If you really want to convert '111201' to 'December 01 2011 00:00am +0000' then set the date formatter's timezone to GMT like this:

self.dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
0
votes

Try adding this to your date formatter to correct the time zone off of GMT:

self.dateFormatter.timeZone = [NSTimeZone systemTimeZone];