0
votes

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?

1
Presumably the formatter didn't recognize the supplied date string.Hot Licks
That's strange. It worked properly with the en_US locale and the newFormatter but it fails to work properly with the zh_CN locale and formatter. 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
One guesses that there are "restrictions" on the zh_CN locale formatter.Hot Licks

1 Answers

0
votes

dateFromString: is not guaranteed or maybe even not supposed to parse date string that came from stringFromDate:. Typical usage scenario is to explicitly set the format of NSDateFormatter and expect date strings to be in this format.

For parsing internet dates like dates from headers in network protocols, it's a good idea to also set formatter's locale to en_US_POSIX, because by default user's current locale will be used.