我想用字符串"2012-11-22 10:19:04"以"2012年9月20日"的格式显示日期.我怎样才能做到这一点?是否有适用于iOS的内置方法?
Din*_*aja 58
NSString *myString = @"2012-11-22 10:19:04";
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *yourDate = [dateFormatter dateFromString:myString];
dateFormatter.dateFormat = @"dd-MMM-yyyy";
NSLog(@"%@",[dateFormatter stringFromDate:yourDate]);
Run Code Online (Sandbox Code Playgroud)
你的日志会像这样打印出来. 22-Nov-2012
试试这个,
NSString *originalDateString = @"2012-11-22 10:19:04";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//2012-11-22 10:19:04
Run Code Online (Sandbox Code Playgroud)
然后用它来解析日期字符串,
NSDate *date = [dateFormatter dateFromString:originalDateString];
Run Code Online (Sandbox Code Playgroud)
您可以创建一个新的dateformatter以新格式打印,或者只重复使用现有格式,
[dateFormatter setDateFormat:@"dd-MMM-yyyy"];//22-Nov-2012
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(@"Date in new format is %@", formattedDateString);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45633 次 |
| 最近记录: |