Reputation: 884
i have and function that convert string to date. and its working very fine but when i try to convert 20130331 the application crashs. and here my code
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(@"before %@ dateStr %@",date,dateStr);
the log is is following
2013-01-02 17:56:04.402 jana2ez[6067:11303] before 2013-03-28 22:00:00 +0000 dateStr 20130329
2013-01-02 17:56:04.498 jana2ez[6067:11303] before 2013-03-29 22:00:00 +0000 dateStr 20130330
2013-01-02 17:56:04.626 jana2ez[6067:11303] before (null) dateStr 20130331
any idea??
Upvotes: 2
Views: 252
Reputation: 884
After hours of bad results, finally I found a solution inspired from @Echihl's comment.
I changed the time in the date so the date will be parsed to same date found in dateStr
.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd HHmm"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(@"before %@ dateStr %@",date,dateStr);
My output becomes
before 2013-03-31 05:00:00 +0000 dateStr 20130331 0800
Previously 20130329 was parsed to March 28th, 2013, at 10 PM
Upvotes: 0
Reputation: 47739
NSCalendar* gregCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[dateFormat setCalendar:gregCalendar];
Upvotes: 1