Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

ios - NSDateFormatter dateFromString Always Returns nil

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;

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.

This is the dateString I'm passing to dateFromString:

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

Thanks for the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two issues here:

  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").

  2. 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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...