日期格式化程序不起作用?

时间:2016-11-30 07:02:42

标签: ios objective-c iphone nsdateformatter

我想将我的日期格式从“MM / dd / YYYY HH:mm:ss”更改为“EEE dd MMM yyyy hh:mm a”,但是如果我的输入为11,我使用的代码不起作用/ 30 / 2016T01:04:30我将月份改为12月,任何人都可以帮助哪里出错?

NSString * date = @"11/30/2016T01:04:30";
date = [date stringByReplacingOccurrencesOfString:@"T" withString:@" "];

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM/dd/YYYY HH:mm:ss"];
NSDate *myDate = [df dateFromString: date];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE dd MMM yyyy hh:mm a"];
NSString *dayName= [dateFormatter stringFromDate:myDate];
NSLog(@"the converted Day  %@",dayName);

1 个答案:

答案 0 :(得分:2)

不需要这个

// date = [date stringByReplacingOccurrencesOfString:@"T" withString:@" "];

使用

 NSDateFormatter *df = [[NSDateFormatter alloc] init];
 NSString * date = @"11/30/2016T01:04:30";

[df setDateFormat:@"MM/dd/yyyy'T'HH:mm:ss"];
NSDate *myDate = [df dateFromString: date];

[df setDateFormat:@"EEE dd MMM yyyy hh:mm a"];
NSString *dayName= [df stringFromDate:myDate];
NSLog(@"the converted Day  %@",dayName);

输出

the converted Day  Wed 30 Nov 2016 01:04 AM