Question

I have this method to convert my MySQL date to NSDate ... what am I doing wrong, the date comes out as nil?

- (NSDate *)dateFromMySQLString {
    if (self == nil) return nil;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"Y-m-d H:i:s"];
    NSDate *date = [dateFormatter dateFromString:self];
    return date;
}

This is from a category on NSString and the value of self is @"2014-02-12 09:03:44".

Était-ce utile?

La solution

It looks like you're using PHP-style date format strings. This isn't what NSDateFormatter uses. NSDateFormatter's documentation says:

The format string uses the format patterns from the Unicode Technical Standard #35.

I think the format pattern you're looking for is yyyy-MM-dd HH:mm:ss. Replace your date format string with that one, and you should start getting the NSDate objects you want.

Autres conseils

Dates are coming nil because your dateFormatter is not right, you have to use this :

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

Hope this helps you.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top