NSDateFormatter dateFromString returns invalid year

I have the following snippet.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat : @"yyyy/MM/dd"];
NSString *timeStr = @"2015/05/16";
NSDate *timeDate = [formatter dateFromString:timeStr];

But when I print timeDate in the console, the output will be werid.The year becomes 4003.

4003-05-16 16:00:00 +0000

I am testing it in iPad 8.3 (12F69) (not a simulator). The system time zone is Beijing. Any help is appreciated.

+4
source share
2 answers

The problem is localeformatting. If you want to use the gregorian calendar regardless of device settings, you should usually set the locale en_US_POSIX.

formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];

. Apple Q & A # 1480. RFC 3339/ISO 8601, , (.. , , ).

+4

... .

NSString *timeStr = @"2015/05/16";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd";
NSDate *Date = [formatter dateFromString:timeStr];
NSLog(@"Date =%@", [formatter stringFromDate:Date]);
0

Source: https://habr.com/ru/post/1589344/


All Articles