2009-11-27 71 views
1

我想将NSString转换为NSDate。如果iPhone地区设置为英语(美国),它的工作原理非常完美,但是当我将其设置为瑞典语时,则不会。如何在将NSString转换为NSDates时避免语言问题?

我的代码:

[...]  
// 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]]); 
[...] 

登录结果:

[...] 
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 
[...] 

这里的问题是,它希望 “FRE,2009年11月27日... +0100”,但它得到“周五, 2009年11月27日... +0100“。我怎样才能解决这个问题?

+2

'[[[NSDate的页头]的init]保留]':页头已经做了保留,所以你保留太多 – user102008 2010-12-03 23:24:09

回答

6

NSDateFormatter有一个属性locale。尝试:

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

谢谢你的提示。我得到它的工作使用: \t [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@“en_US”]]; /Paul Peelen – 2009-11-27 16:30:44

+0

我不太清楚'systemLocale',但希望它能工作。 :) – 2009-11-27 16:46:13

+1

顺便说一句:该代码中有内存泄漏,你应该autorelease语言环境。 – 2009-11-27 16:47:15