PDA

View Full Version : NSDateFormatter dateFromString returing incorrect result [Resolved]




McBgnr
May 6, 2009, 05:39 AM
Hello,

I am trying to get the date from a dateString using the following code snippet:


NSDate *dateToday = [NSDate date];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"MMM d, YYYY"];
NSString *sDate = [dateFormat stringFromDate:dateToday];
NSLog(sDate);

NSDate *newDate = [dateFormat dateFromString:sDate];

NSString *newDateString = [dateFormat stringFromDate:newDate];
NSLog(newDateString);



But the value that is getting logged for newDateString is Dec 22, 2008 instead of today's date. Am I missing something in my code? Suggestions are welcome.



kanenas
May 6, 2009, 07:36 AM
The 'Y' format specifier is for the ISO week date (http://en.wikipedia.org/wiki/ISO_week_date), a governmental and fiscal calendar that has 364 or 371 days in a year so as to be evenly divisible into weeks. Use 'y' for the Gregorian year. The Unicode date format specs (tr35-4 (http://unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns) for OS 10.4 and tr35-6 (http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns) for 10.5) give the meaning of the 'Y' and 'y' format characters.

McBgnr
May 6, 2009, 07:54 AM
That worked great.. Thanks a bunch kanenas.