NSString to NSDate doesn't work

105 Views Asked by At

now it works with this code:

NSString *myDate = @"06/18/2015 8:26:17 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]];
NSDate *date = [dateFormatter dateFromString:myDate];
[dateFormatter setDateFormat:@"dd.MM. HH:mm"];
NSString *dateString = [dateFormatter stringFromDate:date];
cell.timeLabel.text = dateString;
3

There are 3 best solutions below

6
On BEST ANSWER

You have to set the date format as the string

NSString *myDate = @"06/18/2015 8:26:17 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"];
NSDate *date = [dateFormatter dateFromString:myDate];
//Set New Date Format as you want
[dateFormatter setDateFormat:@"dd.MM. HH:mm"];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]];
NSLog(@"%@",[dateFormatter stringFromDate:date]);
0
On

I think there is nothing wrong in your code Dohi7 because i tested it and the date is displayed correctly with @"dd.MM. HH:mm" and @"dd.MM. H:mm" both format. Please check the value of dateFromString again by printing in the console.

And yeah Ashish is also correct. You don't require to alloc data object and you can directly use dateFromString function which itself returns NSDate object.

0
On

Thank you, now it works with the following code:

NSString *myDate = @"06/18/2015 8:26:17 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]];
NSDate *date = [dateFormatter dateFromString:myDate];
[dateFormatter setDateFormat:@"dd.MM. HH:mm"];
NSString *dateString = [dateFormatter stringFromDate:date];
cell.timeLabel.text = dateString;