【发布时间】:2011-01-11 22:19:01
【问题描述】:
我正在为 iPhone 开发一个应用程序,我需要将 XML 提要中的日期转换为 HH:MM 格式。
我有以下方法不起作用,我不知道我做错了什么。
例如,timeToConvert 字符串为:“Mon, 01 Feb 2010 21:55:00 +0100”(不带引号)
当地区设置为美国时该方法有效(我得到正确的日期),但当我将地区(在设置->常规->国际中)更改为西班牙或其他地区时(在这种情况下,我返回零)。
- (id)timeConvertToHHMM:(NSString *)timeToConvert {
NSString *newPubDate = timeToConvert;
//Let's remove any rubbish from the code
newPubDate = [newPubDate stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//create formatter and format to convert the XML string to an NSDate
NSDateFormatter *originalDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[originalDateFormatter setDateFormat:@"EEE, d MMM yyyy H:mm:ss z"];
//run the string through the formatter
NSDate *formattedDate = [[NSDate alloc] init];
formattedDate = [originalDateFormatter dateFromString:newPubDate];
//Let's now create another formatter to take the NSDate and convert format it to Hours and minutes
NSDateFormatter *newDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[newDateFormatter setDateFormat:@"HH:mm"]; // 24H clock set
// And let's convert it back to a readable string
NSString *calcHHMM = [newDateFormatter stringFromDate:formattedDate];
NSLog(@"CalcHHMM: %@", calcHHMM);
return calcHHMM;
}
任何关于为什么这不起作用的提示,只返回 NULL 将非常受欢迎。
【问题讨论】:
-
您收到错误消息还是返回错误的时间?
-
只返回 NULL... 看起来直到 formattedDate = [originalDateFormatter dateFromString:newPubDate];
-
该代码对我有用,除了它返回转换为我当地时区的时间。当您将示例字符串传递给 formattedDate 时,它的值是多少?
-
好的,由于某种原因,它无法使用您在 originalDateFormatter 中提供的格式解析字符串。不知道为什么它对我有用,但您可能必须在格式化程序上执行 setLocale?此外,当您删除格式末尾的“z”时,它将按原样返回小时而不转换为本地时间。
-
看起来设置中的 REGION 与它有关。当我将其设置为美国时,它可以工作,但是如果我将其设置为西班牙(例如),它会停止工作并返回 NULL... 我尝试添加:[originalDateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@ "es_ES"] 自动释放]];但不起作用...
标签: objective-c cocoa cocoa-touch ios-simulator