将NSString转换为mm/dd/yyyy hh:mm:ss格式的NSDate

3
我的日期字符串是8/5/2011 1:38:13 PM。请问如何将其转换成NSDate类型?
我尝试了:
[dateFormatter setDateFormat:@"mm/dd/yyyy 'T' hh:mm:ss a"];
NSString *currentDate = [dateFormatter stringFromDate:currentDateString];

它返回nil。有什么想法吗?
1个回答

9

返回nil的原因是因为您调用了错误的方法,您的日期字符串中没有T(单引号内的字符 ' 是文字),而PM不是“P.M.”。虽然这些问题没有破坏程序,但也有不正确的部分,例如您尝试将月份解析为分钟,并且您的日期字符串最少可以具有1位数字的月份、日期和小时,因此您不应使用两个说明符来补充它们。请尝试以下方法:

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];

不要忘记释放 dateFormatter :-D - kviksilver
我应该在代码被复制粘贴之前补充一下,问题中的OP没有在问题中放置currentDateString、dateFormatter代码,所以我在顶部添加了它们 :) - Joe
[self dateFromString:@"MM/dd/yyyy hh:mm:ss" andDateString:@"08/01/2013 12:14:14"]; 你好Joe,我无法将这个日期格式转换为NSDate对象。 - Apple

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接