Blios
Blios

Reputation: 729

iOS get NSDate from string?

I want to convert string Thu, Nov 22, 2012 to NSDate.

I've tried this:

NSString *str = @"Thu, Nov 22, 2012";

[dateFormat setDateFormat:@"EEE,MMM dd yyyy"];
NSDate *date = [dateFormat dateFromString:str];
NSLog(@"date: %@",date);

But i'm getting null. What am i doing wrong ?

Upvotes: 2

Views: 514

Answers (2)

calimarkus
calimarkus

Reputation: 9977

Since you are using the correct format letters, you just need to fix commas (and spacing) like that:

EEE, MMM dd, yyyy although one E would even be enough (E, MMM dd, yyyy).

See the format reference.

Upvotes: 2

Paresh Navadiya
Paresh Navadiya

Reputation: 38249

NSString date format and NSDateFormatter should be same:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

NSString *string = @"Thu, Nov 22, 2012";

[dateFormat setDateFormat:@"EEE,MMM dd, yyyy"]; //your date formatter is not correct

NSDate *date = [dateFormat dateFromString:string];
NSLog(@"%@",date);

Upvotes: 1

Related Questions