NSDateFormatter dateFromString始终返回nil [英] NSDateFormatter dateFromString Always Returns nil

查看:248
本文介绍了NSDateFormatter dateFromString始终返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提前道歉,问一个重复的问题,但其他解决方案都没有对我有用。每次我尝试将日期字符串传递给dateFromString函数时,我都会得到nil。自从iOS 7更新以来,我没有看到任何事情发生了变化,但是如果这对于是否仍然以相同的方式起作用有所不同,我现在正在进行更新。

I want to apologize ahead of time for asking a repeat question, but none of the other solutions have worked for me yet. Every time I try to pass a date string to the dateFromString function I get nil. I haven't read anywhere that things have changed since the iOS 7 update, but I am current on updates if that makes a difference on whether or not this still works the same way.

这是我用来从字符串创建日期的代码:

This is the code I'm using to create the date from string:

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
    [dateFormat setLocale:[NSLocale systemLocale]];
    [dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    [dateFormat setFormatterBehavior:NSDateFormatterBehaviorDefault];

    NSDate *date = [[NSDate alloc] init];
    date = [dateFormat dateFromString:dateString];

    return date;

我根据我为阅读此问题而阅读的所有解决方案设置了dateFormat,但这些设置都没有解决问题。 systemLocale肯定是为英语设置的,所以不应该引起任何问题。

I've set up my dateFormat based on all the solutions I've read to solve this problem, but none of these settings have solved by problem. The systemLocale is definitely set up for English so that should not be causing any issues.

这是我传递给dateFromString的dateString:

This is the dateString I'm passing to dateFromString:

Wednesday, October 9, 2013 at 2:40:29 PM Pacific Daylight Time

感谢您的帮助!

推荐答案

这里有两个问题:


  1. 格式化程序所期望的日期字符串的格式( @yyyy-MM-dd hh:mm: ss)与您尝试解析的日期字符串的格式不同( @EEEE,MMMM d,yyyy'at'h:mm:ss a zzzz )。

  1. The format of date string the formatter is expecting (@"yyyy-MM-dd hh:mm:ss") is different from the format of the date string you're trying to parse (@"EEEE, MMMM d, yyyy 'at' h:mm:ss a zzzz").

将格式化程序的语言环境设置为 [NSLocale systemLocale] 导致 [dateFormat dateFromString:] 返回 nil 。将其设置为 [NSLocate currentLocale]

Setting the formatter's locale to [NSLocale systemLocale] is causing [dateFormat dateFromString:] to return nil. Set it to [NSLocate currentLocale].

格式化程序的完整代码应为:

The full code for the formatter should be:

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
    [dateFormat setLocale:[NSLocale currentLocale]];
    [dateFormat setDateFormat:@"EEEE, MMMM d, yyyy 'at' h:mm:ss a zzzz"];
    [dateFormat setFormatterBehavior:NSDateFormatterBehaviorDefault];

    NSDate *date = [dateFormat dateFromString:dateString];

这篇关于NSDateFormatter dateFromString始终返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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