Mob*_*its 3 date nsdate nsstring nsdateformatter ios
我得到的日期字符串是8/5/2011 1:38:13 PM
这种格式.我如何将其转换为NSDate
?
我试过了:
[dateFormatter setDateFormat:@"mm/dd/yyyy 'T' hh:mm:ss a"];
NSString *currentDate = [dateFormatter stringFromDate:currentDateString];
Run Code Online (Sandbox Code Playgroud)
它回来了nil
.有什么想法吗?
它返回nil的原因是因为你调用了错误的方法,T
你的日期字符串中没有(单引号'
中的字符是文字),而PM不是"PM".没有破坏它但不完全正确的事情是你试图将月份解析为一分钟而你的日期字符串可以至少有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];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9548 次 |
最近记录: |