Paul Peelen
Paul Peelen

Reputation: 10329

How can I avoid language issues when converting NSStrings to NSDates?

I'm trying to convert a NSString to an NSDate. If the iPhone region is set to English (USA) it works perfect, but when I set it to Swedish it doesn't.

My code:

[...]    
// Get the date from the post
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"eee, dd MMM yyyy HH:mm:ss ZZZ"];

    int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];

    NSDate *dateFromString = [[[NSDate alloc] init] retain];
    dateFromString = [dateFormatter dateFromString:[[stories objectAtIndex:storyIndex] objectForKey: @"date"]];

    NSLog(@"String: %@", [[stories objectAtIndex:storyIndex] objectForKey: @"date"]);
    NSLog(@"date From string: %@", dateFromString);

    // Set date string
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:MM"];
    NSString *stringFromDate = [formatter stringFromDate:dateFromString];
    stringFromDate = [stringFromDate stringByReplacingOccurrencesOfString:@"\n" withString:@""];

    NSLog(@"StringDate: %@", [dateFormatter stringFromDate:[[NSDate alloc] init]]);
[...]

Log result:

[...]
2009-11-27 16:13:22.804 sportal.se[755:4803] String: Fri, 27 Nov 2009 12:56:13 +0100


2009-11-27 16:13:22.812 sportal.se[755:4803] date From string: (null) 
2009-11-27 16:13:22.819 sportal.se[755:4803] StringDate: fre, 27 nov 2009 16:13:22 +0100 
[...]

The problem here is that it expects "fre, 27 nov 2009 ... +0100", but it gets "Fri, 27 Nov 2009 ... +0100". How can I fix this?

Upvotes: 1

Views: 6634

Answers (1)

Georg Schölly
Georg Schölly

Reputation: 126095

NSDateFormatter has a property locale. Try:

dateFormatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
                                                                  autorelease];

Upvotes: 6

Related Questions