Jack
Jack

Reputation: 1

NSDateFormatter dateFromString produces nil after first call in same method

Before Xcode 4 I used to use NSDate initFromString but it is now deprecated and produces errors in Xcode 4.2. So I jumped over to using NSDateFormatter dateFromString but ran into an issue in a method I call that gets a sunrise date from string and a sunset date from string to determine if it is day or night (so same method). The first call works fine, but the second call returns nil. I decided to see if it was repeatable so I created the following simple method and dumped it into another project in an innocuous place:

- (void)testDateFormatter 
  {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    [formatter setDateFormat: @"yyyy-MM-dd hh:mm:ss Z"];
    NSString *srDateTimeString = @"2011-11-09 07:08:00 -0800";
    NSString *ssDateTimeString = @"2011-11-09 17:08:00 -0800";

    NSDate *sunriseDateTime = [formatter dateFromString: srDateTimeString];
    NSDate *sunsetDateTime  = [formatter dateFromString: ssDateTimeString];

    return;
  }

The first call returns the correct date. The second call returns nil. I have tried several variations (such as creating two separate NSDateFormatters, preinitializing the dates, preinitializing the dates to the current time and then reassigning) but none do the expected thing.

Does anyone know what is going on here? Since I hadn't found any reference to this error anywhere I submitted it to Apple (bug #10420498).

Jack

Upvotes: 0

Views: 691

Answers (1)

user467105
user467105

Reputation:

In the second string, the hour is 17 (24-hour format) but the format string uses hh (lowercase) which is for 12-hour format.

Change the format string to yyyy-MM-dd HH:mm:ss Z.

In the documentation, see Date Formatters which contains a link to the Unicode Date Format Patterns listing each format specifier.

Upvotes: 3

Related Questions