objective-c - NSDateFormatter returns wrong date

只愿长相守 提交于 2019-12-25 07:59:06

问题


I have this piece of code:

 // Convert string to date object
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"MMMM d, YYYY"];
        NSDate *formatDate = [dateFormat dateFromString:self.date];
        NSLog(@"1-%@", self.date);
        NSLog(@"2-%@", formatDate);
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:formatDate];
        NSString *dateCal = [NSString stringWithFormat:@"%d/%d/%d", [components day], [components month], [components year]];
        NSLog(@"3-%@", dateCal);
        milage.date = dateCal;

The first NSLog returns:

1-March 23, 2012

The second:

2-2011-12-25 00:00:00 +0000

The third:

3-25/12/2011

Why does the date change when getting the date from the string and formatting it? I'm expecting the third NSLog (or dateCal) to equal 23/3/2012. I live in the UK so its not to do with the timezone..

Thanks,

Jack


回答1:


Needed to use lower case 'y' in the line:

[dateFormat setDateFormat:@"MMMM d, YYYY"];



回答2:


Have you used the setLocale method?

Also, from the technical Q&A:

If you're working with user-visible dates, you should avoid setting a date format string because it's very hard to predict how your format string will be expressed in all possible user configurations. Rather, you should try and limit yourself to setting date and time styles (via -[NSDateFormatter setDateStyle:] and -[NSDateFormatter setTimeStyle:]).




回答3:


Use [dateFormat setDateStyle:NSDateFormatterLongStyle];
Instead of [dateFormat setDateFormat:@"MMMM d, YYYY"];
Will give you reason as soon as I find it.



来源:https://stackoverflow.com/questions/9841129/objective-c-nsdateformatter-returns-wrong-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!