dateFromString返回一个错误的日期setLocale的

问题描述:

后,我有以下代码:dateFromString返回一个错误的日期setLocale的

 
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); 

我backToDate = newBackToDate =今天期待,但日志显示不同:

 
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 

在这里我们可以看到backToDate成为1999-12-30,为什么会发生这种情况?

+0

想必格式化程序不能识别提供的日期字符串。 – 2013-02-14 16:49:45

+0

这很奇怪。它适用于'en_US'语言环境和'newFormatter',但它无法正确使用'zh_CN'语言环境和'formatter'。人们会期望给定的日期格式化程序正确解析刚刚生成的字符串。这是在哪里运行的?设备还是模拟器?什么版本的iOS?尝试一些其他版本。 – rmaddy 2013-02-14 16:57:29

+0

人们猜测zh_CN区域设置格式化程序存在“限制”。 – 2013-02-14 20:07:36

dateFromString:不能保证或者甚至不应该解析来自stringFromDate:的日期字符串。典型的使用场景是明确设置NSDateFormatter的格式,并期望日期字符串采用这种格式。

对于从网络协议中的头文件解析互联网日期,最好将格式化程序的语言环境设置为en_US_POSIX,因为默认情况下将使用用户当前的语言环境。