【问题标题】:NSDateFormatter dateFromString conversionNSDateFormatter dateFromString 转换
【发布时间】:2013-09-28 16:39:51
【问题描述】:

我在将 NSString 对象转换为 NSDate 时遇到问题。这是我想做的事情: 我正在从 Internet 下载 RSS 消息。我有 NSXMLParser 解析的整个消息。之后,我有像 ,或保存到特定 NSStrings 的部分。我想将元素(包括 RSS 消息的发布日期)转换为 NSDate,以便我可以对它执行一些操作,例如对日期对象执行一些操作(例如排序、在时钟上显示等)。这是我的样子:

“格林威治标准时间 2013 年 9 月 25 日星期三 12:56:57”

我尝试通过这种方式将其转换为 NSDate:

*//theString is NSString containing my date as a text
NSDate *dateNS = [[NSDate alloc] init];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"EEE, dd MMM yyyy hh:mm:ss ZZZ"];
dateNS = [dateFormatter dateFromString:theString];*

但是,执行上述代码后,dateNS 总是显示为 (null)。

我的问题很简单:将日期格式如下的 NSString 转换为 NSDate 对象的正确方法是什么?

顺便说一下,我看过网站 http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns 似乎有很多方法可以格式化特定日期,但我找不到我做错了什么。

【问题讨论】:

  • 您需要 HH 以 24 小时格式表示小时。
  • 好的,现在可以了。我没有设置时区和语言环境(顺便说一句,我仍然不知道为什么我必须这样做)。
  • 但我遇到了另一个问题:将日期从字符串转换为 NSDate 后,它会及时移动 3 小时,例如01.01.2013 11:30 -> 01.01.2013 14:30。为什么?是不是因为错误的 LocaleIdentifier(我在波兰,我为 en_GB 设置了 LocaleIdentifier - 我将其更改为 pl_PL 时遇到了一些问题。时区更改为 Europe/Warsaw)。

标签: objective-c nsdate nsdateformatter


【解决方案1】:

您的问题是您的日期格式化程序与您的日期字符串的堡垒不同: 您应该将日期格式化程序设置为与日期字符串相同的格式

我的例子:

// 将字符串转换为日期

    NSString *beginString = @"Sat, 30 Dec 2013 14:45:00 EEST";
    //beginString = [beginString stringByReplacingOccurrencesOfString:@"EEST" withString:@""];
    //beginString = [beginString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Helsinki"]];
    [dateFormat setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z"];
    dateFromString = [dateFormat dateFromString:beginString];

    //NSLog(@"Begin string: %@", beginString);

    //NSLog(@"not formated: %@", dateFromString);

    // Convert Date to string

    [dateFormat setTimeZone:[NSTimeZone localTimeZone]];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"ru_RU"]];
    [dateFormat setDateFormat:@"dd MMMM yyyy"];
    myStrDate = [dateFormat stringFromDate:dateFromString];
    [currentTitle setPubDate:myStrDate];

【讨论】:

    【解决方案2】:

    NSDate * dateNS = [[NSDate alloc] init];没用,你不需要分配任何日期对象。

    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
    NSLog(@"%@", [dateFormatter dateFromString:@"Wed, 25 Sep 2013 12:56:57 GMT"]);
    

    正确输出日期,你确定theString 不是nil

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多