0

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

Jack
  • 1
  • 1
  • as i was editing i saw you didn't have a () after testDateFormatter, seemed like a typo so I corrected it. just so you know. – AndersK Nov 09 '11 at 21:38
  • @Anders, that wasn't a typo, Objective-C does not put its argument lists in parentheses. – DrGoldfire Nov 09 '11 at 21:41
  • Just to clarify, you made two separate NSDateFormatter objects, sent both of them dateFromString _separately_, with the two separate strings, and this still happened? – DrGoldfire Nov 09 '11 at 21:45
  • Yes, I tried that. I'll try it again on the test method right now. Yup, same results. Just added another formatter and renamed them both to formatter1 and formatter2, etc. The first one works fine, the second one is nil. – Jack Nov 10 '11 at 01:39

1 Answers1

3

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.

  • Well now I feel stupid, but I also appreciate the correction. That works fine of course. Is it possible that when initFromString was still working that hh with a 24-hour clock still worked? I only ask because I have a link to the Unicode Date Format Patterns document right in my code documentation (so that I don't have to keep figuring out where it is). Anyway, I'll go undo my bug to Apple now. – Jack Nov 10 '11 at 16:38