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

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top