如何使用NSDateFormatter解析这些时区? [英] How to parse these time zones with NSDateFormatter?

查看:115
本文介绍了如何使用NSDateFormatter解析这些时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析大量的互联网日期.首先,我尝试使用en_US_POSIX语言环境的格式化程序,然后使用en_GB.该代码看起来或多或少是这样的:

I'm parsing a large number of internet dates. First I try a formatter with en_US_POSIX locale, then with en_GB. The code looks more or less like this:

{
    NSDate *date = [dateString dateWithDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z (zzz)" localeIdentifier:@"en_US_POSIX"];
    if (date) return date;
    date = [dateString dateWithDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z (zzz)" localeIdentifier:@"en_GB"];
    return date;
}

- (NSDate*) dateWithDateFormat:(NSString*)dateFormat localeIdentifier:(NSString*)localeIdentifier
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
    formatter.dateFormat = dateFormat;
    [formatter dateFromString:self];
}

但是,具有以下时区的日期字符串无法解析:

However, date strings with the following time zones fail to parse:

Mon, 16 Jul 2012 12:08:17 +0100 (GMTUK)
Thu, 6 Sep 2012 13:00:06 +0900 (KST)
Wed, 3 Nov 2010 10:12:15 +0100 (Hora est�ndar romance)
Wed, 14 Sep 2011 14:37:35 +0100 (IST)
Wed, 2 May 2012 09:41:06 +0200 (MEST)
Sun, 31 Oct 2010 12:53:06 +0800 (SGT)
Thu, 19 Jan 2012 08:34:44 -0300 (UYT)

我做错了什么?

仅在这些情况下,我应该对字符串进行预处理以删除时区括号吗?

Should I pre-process the strings to remove the time zone parenthesis in these cases only?

推荐答案

NSDate可以存储没有时区信息的时间点.由您的软件决定是否特定的NSDate实例将时间点存储在UTC还是本地时区中.在大多数情况下,您想使用UTC日期.

NSDate can store a point in time without timezone information. It's up to your software to know whether a specific NSDate instance stores the point in time in UTC or in the local time zone. In most cases, you want to use UTC dates.

因此,在解析日期时处理时区差异很重要.但是不可能记住日期最初所在的时区(至少不能仅使用NSDate实例).

Because of that, it's important to handle time zone differences when parsing the dates. But it's not possible to remember the time zone the dates was originally in (at least not with an NSDate instance only).

因此,我建议您切断括号中的时区,并在其之前解析数字时区偏移量.这样,您可以将所有字符串转换为UTC中的NSDate实例,并且在解析字符串时应该没有任何问题.

So I would recommend that you cut off the time zone in parenthesis and just parse the numerical time zone offset before it. That way, you can convert all strings into an NSDate instance in UTC and you shouldn't have any problems parsing the strings.

那不应该是起始日期(例如,大写Z表示数字时区偏移量)吗?

And shouldn't the date fromat be (i.e. uppercase Z for a numeric time zone offset)?

@"EEE, dd MMM yyyy HH:mm:ss ZZZ"

这篇关于如何使用NSDateFormatter解析这些时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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