开发者

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 Swed开发者_开发百科ish 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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜