fannheyward fannheyward - 2 years ago 85
iOS Question

NSDateFormatter error, return date one year ago

Code:

NSString *ds = @"2013-02-25";
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd"];
NSDate* date = [formatter dateFromString:ds];
NSLog(@"%@", date); //2012-02-24 16:00:00 +0000
[formatter setDateFormat:@"MMM dd, YYYY"];
NSLog(@"%@", [formatter stringFromDate:date]); //Feb 25, 2012


Is there something wrong I made? Or iOS 6 SDK bug?

Answer Source

Change this :

[formatter setDateFormat:@"YYYY-MM-dd"];
[formatter setDateFormat:@"MMM dd, YYYY"];

To :

[formatter setDateFormat:@"yyyy-MM-dd"];
[formatter setDateFormat:@"MMM dd, yyyy"];

Reason for the error,

It's a common mistake to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download