NSDateFormatter返回nil

时间:2011-10-06 14:19:40

标签: objective-c nsdateformatter

任何人都可以告诉我为什么这段代码在我的日志文件中返回nil:

    NSString *dateString = [[NSString alloc] initWithString: @"2011-08-23 15:00"];

NSLocale *englishLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-mm-dd HH:MM"];
[dateFormatter setLocale:englishLocale];

NSLog(@"%@",[dateFormatter dateFromString:dateString]);

非常感谢。

3 个答案:

答案 0 :(得分:6)

检查我的变体:

NSString *dateString = [[NSString alloc] initWithString: @"2011-08-23 15:00"];

NSLocale *englishLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//HH:MM -> HH:mm
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
[dateFormatter setLocale:englishLocale];

NSLog(@"%@",[dateFormatter dateFromString:dateString]);

如您所见,我已将日期格式更改为:@"yyyy-MM-dd HH:mm"

所有格式均可在此处找到:UNICODE LOCALE DATA MARKUP LANGUAGE (LDML)

答案 1 :(得分:3)

你应该是正确的'HH:MM'到'HH:mm'

NSString *dateString = [[NSString alloc] initWithString: @"2011-08-23 15:00"];

    NSLocale *englishLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //HH:MM -> HH:mm
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    [dateFormatter setLocale:englishLocale];

    NSLog(@"%@",[dateFormatter dateFromString:dateString]);

答案 2 :(得分:0)