它返回nil的原因是因为你调用了错误的方法,日期字符串中没有T
(单引号内的字符是文字),并且PM不是“P.M.”。没有打破它但不完全正确的事情是,你试图解析一个月为一分钟,你的日期字符串可以有最少1位数的月份,日期和小时,所以你不应该使用2填充它们的说明符如果你是从日期创建一个字符串。试试这个:
NSString *currentDateString = @"8/5/2011 1:38:13 PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Set the AM and PM symbols
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
//Specify only 1 M for month, 1 d for day and 1 h for hour
[dateFormatter setDateFormat:@"M/d/yyyy h:mm:ss a"];
NSDate *currentDate = [dateFormatter dateFromString:currentDateString];
NSLog(@"current date: %@", currentDate);
//Example of the format using the actual date
NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);
[dateFormatter release];
来源
2011-08-05 18:00:38
Joe
不要忘记释放dateFormatter :-D – kviksilver
我也许应该补充一点,之前的代码是复制粘贴:),在OP没有把currentDateString,在这个问题dateFormatter代码,所以我只是添加到顶部:) – Joe
[self dateFromString:@“MM/dd/yyyy hh:mm:ss”andDateString:@“2013-08-01 12:14:14”]; hello joe ,,我没有在NSDate对象中获取这种格式的日期 – Apple