Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http Date to NSDate

I have a string taken from an http response header field "Date" in this format:

"Sun, 24 Jun 2012 16:34:51 GMT"

what i want is to convert this string in a NSDate object. For this scope I have instantiated an NSDateFormatter using various format:

[dateFormatter setDateFormat:@"EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz"];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss zzz"];
[dateFormatter setDateFormat:@"EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss 'GMT'"];

but when I print the string from date using:

[dateFormatter dateFromString:date]

I receive:

(null)

where am I doing wrong?

like image 415
LuckyStarr Avatar asked Jun 24 '12 16:06

LuckyStarr


1 Answers

Not sure I understand the problem, as your own code seems to work fine for me:

NSString *dateStr = @"Sun, 24 Jun 2012 16:34:51 GMT";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz"];

NSDate *date = [dateFormatter dateFromString:dateStr];

NSLog(@"Date: %@", date);

Which gives this output:

Date: 2012-06-24 16:34:51 +0000

Unless I have misunderstood your question, this is the correct result.

like image 60
Monolo Avatar answered Sep 29 '22 10:09

Monolo