0

我有这段代码在 iOS 6 中非常有用,可以将这个 Rails json 提供的日期字符串转换为 NSDate (2012-12-11T08:28:16-08:00):

NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
return [formatter dateFromString:string];

但它在 iOS 5 上不起作用。我找不到任何好的资源来转换 5 中的日期。感谢您的帮助。

4

3 回答 3

0

iOS 6.0 使用 UTS 版本 tr35-25 进行格式化。使用 5 'Z's 作为时区解析类似于 -08:00 的内容。IE:

[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];

iOS 5 和 5.1 使用版本 tr35-19,它没有为 -08:00 指定任何内容,尽管 3 'Z' 用于类似 -0800 的内容。

改变'Z's的工作量吗?

您可以在此处找到格式规范:

悉尼科技大学 #35-19

悉尼科技大学 #35-25

于 2013-04-03T19:18:05.787 回答
0

在解析字符串之前,您需要从末尾的时区中删除冒号。

当我解析 +01:00 时,这对我来说更容易,但你可以使用

[dateString componentsSeparatedByString:@"-"]

要获取一组组件,最后一个是时区,请删除冒号

[timeZoneString stringByReplacingOccurrencesOfString:@":" withString:@""]

然后将所有组件重新附加在一起,并在每个组件之间替换为“-”。

于 2013-04-03T19:53:03.537 回答
0
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];    
NSString *clearedString = [railsDateString stringByReplacingOccurrencesOfString:@":" withString:@"" options:0 range:NSMakeRange(22, 1)];
NSDate *date = [dateFormat dateFromString:clearedString];

更清洁的詹姆斯 P 版

于 2014-07-21T15:47:39.130 回答