Search code examples
iphonensdatensdateformattergmtnstimezone

iPhone - Strange problem with NSDate, NSString, and Timezones


I've searched and haven't found an exact question like mine, so here goes nothing:

I have a NSString containing a key that I pull from an XML feed. The key is a time in 24-hour format (e.g. 13:30 or 15:00.) I'd like to convert the NSString to an NSDate and have it converted to the appropriate timezone based on the device's set timezone. The key is Unicode HH:mm (24:00), so I'm curious why this does not work as it should.

I've already gotten a basic outline that should work, but alas does not. The 2nd NSLog (Got NS Date) returns null and the final log returns a strange number (1969-12--2147483629 -596:-31:-23 +0000 to be precise.) What am I doing wrong here?

Thanks in advance,

    NSString *dateString = [dict objectForKey:@"24hrdate"];
    NSLog(@"NSString Date: %@", dateString);

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    
    [formatter setDateFormat:@"HH:mm"];
    NSDate *sourceDate = [formatter dateFromString:dateString]; 
    NSLog(@"Got NS Date: %@", sourceDate);

    NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSTimeZone *destinationTimeZone = [NSTimeZone systemTimeZone];

    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

    NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
    NSLog(@"Final Date: %@", destinationDate);

Solution

  • First of all understand that the date component will be 01-01-1970 because it isn't provided. I am assuming that you want the time to be 04:00 GMT if the input string is @"04:00". That you can achieve by setting the time zone of the formatter.

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    [formatter setDateFormat:@"HH:mm"];
    NSDate *sourceDate = [formatter dateFromString:dateString];