2016-11-30 41 views
0

我想将日期格式从“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); 
+0

你想要的东西放出来就告诉我 –

+0

@HimanshuM oradiya希望将MM/dd/YYYY HH:mm:ss--格式转换为--EEE dd MMM yyyy hh:mm a - – Arun

+2

@Arun您在第一次约会时因为大写'YYYY'而面临此问题Formate它应该是小'yyyy'也不需要使用两个dateFormatter,你可以使用单一的一次,而不是使用空格替换'T',只需将dateFormate更改为'MM/dd/yyyy'T'HH:mm: ss' –

回答

1

不需要这个

// 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 
+0

坦斯克兄弟安布:) .. – Arun

+0

也检查你的时区也,如果你需要 –

+0

karthick解决frnd坦克你:) – Arun