Daniel Chen
Daniel Chen

Reputation: 2033

dateFromString returned a wrong date after setLocale

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?

Upvotes: 0

Views: 258

Answers (1)

eofster
eofster

Reputation: 2047

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.

Upvotes: 0

Related Questions