[英]How can I avoid language issues when converting NSStrings to NSDates?
我正在嘗試將NSString轉換為NSDate。 如果將iPhone區域設置為英語(美國),則可以正常使用,但是當我將其設置為瑞典語時,則不能。
我的代碼:
[...]
// 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”,但它的值為“ Fri,2009年11月27日... + 0100”。 我怎樣才能解決這個問題?
NSDateFormatter
具有屬性locale
。 嘗試:
dateFormatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
autorelease];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.