DoHi7
DoHi7

Reputation: 21

NSString to NSDate doesn't work

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;

Upvotes: 0

Views: 94

Answers (3)

DoHi7
DoHi7

Reputation: 21

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;

Upvotes: 0

sajgan2015
sajgan2015

Reputation: 305

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.

Upvotes: 0

Ashish Kakkad
Ashish Kakkad

Reputation: 23872

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

Upvotes: 2

Related Questions