NSDateFormatter dateFromString Always Returns nil

前端 未结 7 731
不知归路
不知归路 2020-12-06 10:19

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 dateFro

相关标签:
7条回答
  • 2020-12-06 10:29

    In case anybody is stuck on the same hilarious edge case as me:

    "2020-03-08T02:00:00" will return nil as long as you're in a locale that follows Daylight Savings Time, because that hour is skipped and simply doesn't exist.

    0 讨论(0)
  • 2020-12-06 10:32

    According to NSDateFormatter documentation :

    When working with fixed format dates, such as RFC 3339, you set the dateFormat property to specify a format string.

    If your date format is 2017-06-16T17:18:59.082083Z then dateFormat property should look like this yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ.

    Swift 3

    let dateFormatter = DateFormatter()
    let date = "2017-06-16T17:18:59.082083Z"
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
    
    let result = dateFormatter.date(from: date) // 2017-06-16 17:18:59 +0000
    
    0 讨论(0)
  • 2020-12-06 10:37

    You're trying to use dateFromString but the Format you have passed to your Formatter is different of what you're using in dateString.

    Try to use this config in your dateFormat: E',' M d',' yyyy 'at' hh:mm:ss aa z

    0 讨论(0)
  • 2020-12-06 10:40

    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];
    
    0 讨论(0)
  • 2020-12-06 10:43

    Yet another way to get nil is if you use hh and your hours are on the 24 hr clock and > 12, in that case, you need HH (or H, for zero-padded).

    That is:

    • Format: yyyy-MM-DD hh:mm:ss, string: "2016-03-01 13:42:17" will return nil
    • Format: yyyy-MM-DD HH:mm:ss, string: "2016-03-01 13:42:17" will return the date you expect.

    Hat-tip to @neilco (see comments below his answer) for this. If you like this answer, please up-vote his, too.

    0 讨论(0)
  • 2020-12-06 10:43

    Don't forget to escape "yyyy/MM/dd' 'HH:mm:ss" space symbols

    0 讨论(0)
提交回复
热议问题