NSDateFormatter dateFromString Always Returns nil

前端 未结 7 752
不知归路
不知归路 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: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];
    

提交回复
热议问题