1
votes

I am trying to convert an string date to a NSDate to make some changes in the format.. but it is always returning nil!

This is my code:

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

//Mon Jan 30 17:40:12 +0000 2012
[df setDateFormat:@"ccc MMM dd HH:mm:ss Z yyyy"];
[df setTimeStyle:NSDateFormatterFullStyle];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

NSDate *date1 = [df dateFromString:strData];

I have tried this format too:

[df setDateFormat:@"EEE MMM dd HH:mm:ss z yyyy"];

I have tried this table:

http://www.deanoj.co.uk/ios-development/nsdateformatter-formatting-strings-reference/

I have tried these links.. and a lot of others:

Convert NSString to NSDate with string format "Sun, 08 Jan 2012 13:57:38 +0000"

NSDateFormatter dateFromString returns nil

How to format Facebook/Twitter dates (from the JSON feed) in Objective-C

Could someone help me please?

Thanks in advance!

1
Don't forget to release the allocated NSLocale, otherwise it will leakJustSid

1 Answers

2
votes

If I take your code and modify it to this:

[df setDateFormat:@"ccc MMM dd HH:mm:ss Z yyyy"];
// [df setTimeStyle:NSDateFormatterFullStyle];
// [df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

NSDate *date1 = [df dateFromString:@"Mon Jan 30 17:40:12 +0000 2012"];
NSLog( @"date is %@", date1);

I'm getting:

2012-01-30 11:36:38.339 TestApp[32182:f803] date is 2012-01-30 17:40:12 +0000

Seems like all you should need to do is comment (or remove) those two lines.