1

I am getting date from json in format "1/31/2016 5:53:21 AM" & i want to convert it to the format "31 Jan'16"...

I tried this code..

myDate=@"01/31/2016 05:53:21 AM";
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd/MM/yyyy hh:mm:ss tt";
NSDate *dtNew = [dateFormatter dateFromString:myDate];
dateFormatter.dateFormat = @"dd MMM'YY";
NSLog(@"%@",[dateFormatter stringFromDate:yourDate]);

but myDate string can't convert to NSDate. & dtNew comes nil.

Anyone can help?

Thanks in advance.!!!

Anbu.Karthik
  • 77,564
  • 21
  • 153
  • 132
Sneha
  • 842
  • 8
  • 23
  • What you have tried so far? – Vizllx Feb 02 '16 at 05:14
  • Possible duplicate of [NSDate and NSDateFormatter - short format date and time in iphone sdk](http://stackoverflow.com/questions/936969/nsdate-and-nsdateformatter-short-format-date-and-time-in-iphone-sdk) – Vizllx Feb 02 '16 at 05:26

2 Answers2

2

try this

 NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
                          // "1/31/2016 5:53:21 AM" // initial date
dateFormatter.dateFormat = @"MM/dd/yyyy hh:mm:ss a";
NSDate *dtNew = [dateFormatter dateFromString:@"1/31/2016 5:53:21 AM"];
                          // 31 Jan'16 // second date
dateFormatter.dateFormat = @"dd MMM''yy";
NSLog(@"%@",[dateFormatter stringFromDate:dtNew]);

final output is

enter image description here

Anbu.Karthik
  • 77,564
  • 21
  • 153
  • 132
0

Try this, you should use format ending 'a' and double ' to escape it.

NSString *myDate=@"01/31/2016 05:53:21 AM";
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *dtNew = [dateFormatter dateFromString:myDate];
dateFormatter.dateFormat = @"dd MMM''yy";
NSLog(@"%@",[dateFormatter stringFromDate:dtNew]);
Muhammad Nabeel Arif
  • 18,528
  • 8
  • 48
  • 70