views:

1242

answers:

1

Hi,

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".

Best regards, Paul Peelen

+3  A: 

NSDateFormatter has a property locale. Try:

dateFormatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
                                                                  autorelease];
Georg
Thanks for the tip. I got it working using: [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];/Paul Peelen
Paul Peelen
I wasn't quite sure about `systemLocale` but hoped it would work. :)
Georg
BTW: There's a memory leak in that code, you should autorelease the locale.
Georg