-1

I am trying to set an NSDate from a string. The format of the string looks like this (RFC 2822):

Tue, 09 Jun 2015 06:09:38 +0000

The code I am using is:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier: @"en_US_POSIX"];
dateFormatter.dateFormat = @"EEE, dd MMM yyyy hh:mm:ss Z";
NSDate *dateString = [dateFormatter dateFromString:self.time];

But dateString always returns a nil. self.time definitely contains the string for the time.

spogebob92
  • 1,474
  • 4
  • 23
  • 32
  • This has been asked thousands of times already. Why did you feel it was necessary to create a new question? – Fogmeister Jun 19 '15 at 09:55
  • Because I believed it to be out of the ordinary due to not being able to see an obvious error with dateFormat, locale, etc. – spogebob92 Jun 19 '15 at 09:57

3 Answers3

2

I think your self.time is either nil or in some other format. To check your code put string manually and see the result

NSString *str = @"Tue, 09 Jun 2015 06:09:38 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier: @"en_US_POSIX"];
dateFormatter.dateFormat = @"EEE, dd MMM yyyy hh:mm:ss Z";
NSDate *dateString = [dateFormatter dateFromString:str];
NSLog(@"date : %@",dateString);

I added a sample it gave me correct result. Try once to debug the value of self.time

Kamal Bhardwaj
  • 948
  • 1
  • 10
  • 25
1

If I do this this works absolutely fine

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier: @"en_US_POSIX"];
    dateFormatter.dateFormat = @"EEE, dd MMM yyyy hh:mm:ss Z";
    NSDate *dateString = [dateFormatter dateFromString:@"Tue, 09 Jun 2015 06:09:38 +0000"];

output is : 2015-06-09 06:09:38 +0000

Ankit Sachan
  • 7,690
  • 16
  • 63
  • 98
0

You possibly need to set timezone. [dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];

Rajesh
  • 546
  • 9
  • 29