Sneha Sneha - 6 months ago 15
iOS Question

Format "1/31/2016 5:53:21 AM" to "31 Jan'16" in iOS

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.!!!

Answer

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

Comments