dateFromString在setLocale之后返回了错误的日期

时间:2013-02-14 16:34:53

标签: objective-c nsdate nslocale

我有以下代码:

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,为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

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

为了解析互联网日期,例如网络协议中标题的日期,最好还将格式化程序的区域设置设置为en_US_POSIX,因为默认情况下用户的当前区域设置将是使用