Arun Arun - 9 days ago 6
iOS Question

Date Formatter not working?

I want to change my date format from "MM/dd/YYYY HH:mm:ss" to "EEE dd MMM yyyy hh:mm a", but the code I am using not working for example if my input is 11/30/2016T01:04:30 I am getting the month changed as December, can any one help where is the mistake?

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);

Answer

no need of this

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

use like

 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);

Output:

the converted Day  Wed 30 Nov 2016 01:04 AM