NSDateFormatter dateFromString返回null

时间:2012-02-06 21:57:13

标签: objective-c nsstring nsdateformatter

我正在尝试将字符串日期转换为日期对象,以便我可以进行一些比较。我的代码如下:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy/MM/dd_hh:mm:ss"];
NSDate *date = [formatter dateFromString:@"2012/02/06_20:35:59"]; 
[formatter release];

NSLog(@"date = %@", date);

我的NSLog显示* date = null;

感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:6)

您的格式不是yyyy/MM/dd_HH:mm:ss吗?

hh为0-12,HH为0-23。

供参考,以下是我从中获取信息的文档 - http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns

答案 1 :(得分:3)

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [formatter dateFromString:@"2012-02-06 20:35:59"]; 
    [formatter release];

    NSLog(@"date = %@", date);


d Day of the month as digits; no leading zero for single-digit days.
dd Day of the month as digits; leading zero for single-digit days.
ddd Day of the week as a three-letter abbreviation.
dddd Day of the week as its full name.
m Month as digits; no leading zero for single-digit months.
mm Month as digits; leading zero for single-digit months.
mmm Month as a three-letter abbreviation.
mmmm Month as its full name.
yy Year as last two digits; leading zero for years less than 10.
yyyy Year represented by four digits.
h Hours; no leading zero for single-digit hours (12-hour clock).
hh Hours; leading zero for single-digit hours (12-hour clock).
H Hours; no leading zero for single-digit hours (24-hour clock).
HH Hours; leading zero for single-digit hours (24-hour clock).
M Minutes; no leading zero for single-digit minutes.
Uppercase M unlike CF timeFormat‘s m to avoid conflict with months.
MM Minutes; leading zero for single-digit minutes.
Uppercase MM unlike CF timeFormat‘s mm to avoid conflict with months.
s Seconds; no leading zero for single-digit seconds.
ss Seconds; leading zero for single-digit seconds.