views:

1123

answers:

2

I'm trying to parse dates using the user's date preferences

[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSDate *date = [ dateFormatter dateFromString:@"7/4/2008" ];
NSLog(@"string from date %@: %@ for locale %@", date, [dateFormatter stringFromDate:date], [[dateFormatter locale] localeIdentifier]);

When I set my region (in the International system preferences) to be United States, it prints:

2008-08-14 20:20:31.117 Date Difference17226:10b string from date 2008-07-04 00:00:00 -0400: 7/4/08 for locale en_US

And when my region is United Kingdom, it prints:

2008-08-14 20:19:23.441 Date Difference17199:10b string from date 2008-04-07 00:00:00 -0400: 07/04/2008 for locale en_GB

It looks like the NSDateFormatter is insensitive to the change of regions. Notice that the raw printing of the date is properly switching with the region, though.

What do I have to do to get the NSDateFormatter to respect the region setting?

A: 

This looks correct. In the first output sample, the formatted date string is 7/4/200. In the second, it is 07/04/2008.

What difference were you expecting?

If you did not change your format preferences for the United Kingdom preferred date format, I believe it defaults to MM/DD/YYYY with leading zeros for months and days less than 10.

+3  A: 

It looks like the NSDateFormatter is insensitive to the change of regions.

No, it is using the locale in both directions.

You can see how the formatter interpreted the date by looking at the date's description (the first %@ in your NSLog format).
With the region as US, the formatter interpreted the date as 2008-07-04 (July 4).
With the region as GB, the formatter interpreted the date as 2008-04-07 (April 7).

Then, you asked the same formatter in the same region to display that date.
July 4 using US format is 07/04/2008 (MM/DD/YYYY).
April 7 using GB format is 07/04/2008 (DD/MM/YYYY).

Peter Hosey