문제

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