简体   繁体   中英

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?

NSDateFormatter has a property locale . Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM