NSDate returning nil in iOS

204 views Asked by At

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.

3

There are 3 answers

0
Rajesh On

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

2
Kamal Bhardwaj On

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

0
Ankit Sachan On

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