Reputation: 455
I encountered a small problem today: I receive a couple of dates (NSString) from a web server. To use those dates correctly they need to be parsed into NSDate objects, for which I'm using the following code:
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"dd.MM.yyy HH:mm:ss";
return [formatter dateFromString:dateString]
The dates I am receiving are in the following format e.g.: @"02.06.2015 13:31:24".
My problem is that the above code returns nil. I think the issue probably is that I don't have the correct format string, which I have not been able to get right..
Any help would be highly appreciated!
Upvotes: 0
Views: 95
Reputation: 1741
-(NSDate *)getDateFromString:(NSString *)string
{
NSString * dateString = [NSString stringWithFormat: @"%@",string];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd.MM.yyyy HH:mm:ss"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
return myDate;
}
Call it wherever required :)
[self getDateFromString:@"13.07.2013 16:22:11"];
Upvotes: 0
Reputation: 2654
Please try below code -
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"dd.MM.yyyy HH:mm:ss";
return [formatter dateFromString:dateString]
Upvotes: 0
Reputation: 7107
You are missing a 'y' in your format. It should be:
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"dd.MM.yyyy HH:mm:ss";
return [formatter dateFromString:dateString]
Upvotes: 3