I guess I don’t understand how to properly manage timezone. I have a date object that is generated from various methods, including UIDatepicker, which uses the device timezone for the UI and generates a date object with UTC+0000.
I’m also trying to extract just the 4-digit year from the date object, but I’m getting an unexpected result. I thought the problem was that I needed to apply a timezone to the date formatter, but that doesn’t seem to have helped. Here is my code:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
[dateFormat setTimeZone:currentTimeZone];
[dateFormat setDateFormat:@"YYYY"];
NSLog(@"About to use self.displayedDate: %@",self.displayedDate);
NSString *gregorianYear = [dateFormat stringFromDate:self.displayedDate];
NSLog(@"Calculated Gregorian year: %@ from date %@",gregorianYear,self.displayedDate);
I’m currently in CST. When I run this, I get the following output:
2013-01-06 21:22:47.168 293 Calendar[4835:907] About to use self.displayedDate: 2012-12-31 03:22:26 +0000
2013-01-06 21:22:47.171 293 Calendar[4835:907] Calculated Gregorian year: 2013 from date 2012-12-31 03:22:26 +0000
The date in my app is originally set from the current date/time. Then I use the UIDatePicker control configured only for dates to set the date to December 30 2012 (that’s what displays on the UIDatePicker control). The return value from the datepicker is plugged directly into the code that produced the above output. It seems obvious to me that it should produce 2012 instead of 2013, so I must be missing something.
Don´t use the format symbols: “YYYY”! use “yyyy” instead!
“YYYY” is the week year, which is not what you want!
See also Converting NSString to NSDate adds one year in some cases