I have following codes:
NSDate *today = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSLocale *zh_CN = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
[formatter setLocale:zh_CN];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
NSDateFormatter *newFormatter = [[NSDateFormatter alloc]init];
NSLocale *en_US = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
[newFormatter setLocale:en_US];
[newFormatter setDateStyle:NSDateFormatterFullStyle];
[newFormatter setTimeStyle:NSDateFormatterNoStyle];
NSLog(@"today: %@", today);
NSString *todayString = [formatter stringFromDate:today];
NSLog(@"zh_CN todayString: %@", todayString);
NSDate *backToDate = [formatter dateFromString:todayString];
NSLog(@"zh_CN backToDate: %@", backToDate);
NSString *newTodayString = [newFormatter stringFromDate:today];
NSLog(@"en_US newTodayString: %@", newTodayString);
NSDate *newBackToDate = [newFormatter dateFromString:newTodayString];
NSLog(@"en_US newBackToDate: %@", newBackToDate);
I was expecting backToDate = newBackToDate = today, but the log shows different:
2013-02-15 00:18:12.594 TestNSDate[16637:11303] today: 2013-02-14 16:18:12 +0000 2013-02-15 00:18:12.595 TestNSDate[16637:11303] zh_CN todayString: 2013年2月15日星期五 2013-02-15 00:18:12.596 TestNSDate[16637:11303] zh_CN backToDate: 1999-12-30 16:00:00 +0000 2013-02-15 00:18:12.619 TestNSDate[16637:11303] en_US newTodayString: Friday, February 15, 2013 2013-02-15 00:18:12.620 TestNSDate[16637:11303] en_US newBackToDate: 2013-02-14 16:00:00 +0000
Here we can see the backToDate was became 1999-12-30, why would this happen?
en_USlocale and thenewFormatterbut it fails to work properly with thezh_CNlocale andformatter. One would expect a given date formatter to properly parse a string that it just generated. Where was this run? device or simulator? What version of iOS? Try some other versions. - rmaddy