根据用户设置将JSON日期解析为NSDate [英] Parse JSON date into NSDate depending user settings

查看:127
本文介绍了根据用户设置将JSON日期解析为NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在转换brut JSON字符串日期时遇到问题:

I have a problem for converting a brut JSON string date:

"created_at" ="2012-12-22T21:39:22Z";

"created_at" = "2012-12-22T21:39:22Z";

进入NSDate.

这是我目前的类别:

- (NSDate*)dateWithJSONString
{
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[dateFormatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:self];
return date;        
}

问题是这适用于我95%的情况,但是如果某些用户在该日期和时间设置与自定义国际设置结合使用AM/PM而不是24H,则日期不是从json字符串创建的.

The problem is this works for 95% of my cases, but if some users use AM/PM instead of 24H in there date and time settings combined with custom international settings, the date is not created from the json string.

我阅读了此讨论,但我做不到找到与所有国际用户和设置一起使用的好方法.

I read this discussion but I can't find the good way to work with all my international users and settings.

我添加了这个例子:

[dateFormatter setLocale:[NSLocale currentLocale]];

但是它什么也没改变.如果我将iPhone设置为AM/PM而不是24H,则不会创建NSDate.

but it changed nothing. The NSDate is not created if I set my iPhone with AM/PM instead of 24H.

AM/PM NSDate模式: 2013-01-21 07:12:43 AM +0000

AM/PM NSDate schema: 2013-01-21 07:12:43 AM +0000

24H NSDate模式: 2013-01-21 07:12:43 +0000

24H NSDate schema: 2013-01-21 07:12:43 +0000

我想念什么?有什么要更新的日期格式吗?

What did I miss ? Is there something to update in the date format ?

推荐答案

您只需要设置正确的dateFormat,其余代码就是正确的.

You just need to set the correct dateFormat, rest of your code is correct.

[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"];

dateString中的字符Z是ISO8601定义的有效日期格式,它表示日期字符串采用UTC时区.因此,您无需将时区设置为格式化程序.格式化程序可以从字符Z识别时区.因此,如果忽略它,除非为dateFormatter指定了时区,否则时区将不匹配.

The character Z in your dateString is a valid date format defined by ISO8601, it denotes that the date string is in UTC timezone. So you don't need to set the timezone to the formatter. Formatter can recognise the timezone from character Z. So if it is ignored there would be mismatches in timezone unless a timezone is specified to dateFormatter.

如果您的dateString不统一,请对dateFormat进行后备检查.检查转换后的日期是否为零,如果为零,则使用后退dateFormat.

If your dateString is not uniform, put a fall back check for dateFormat. Check for converted date to be nil, if nil use the fall back dateFormat.

除非日期字符串和系统日历的日历类型发生更改,否则也无需将日历设置为dateFormatter.

Also no need to set the calendar to dateFormatter unless there is change in the calendar type of date string and system calendar.

这篇关于根据用户设置将JSON日期解析为NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆