0

I've discovered a bug in my app / function. I pass in a NSString of a date. The function then uses the NSDateFotmatterShortStyle.

Heres a screen shot of my function in the debugger.

I'd like to end up with a date of 2011-04-18 Not sure why its added 1ppm either, I need it to be 00:00:00

enter image description here

Whats happening and how do I fix this ?

I use the MidnightUTC function from here ( How do I create the current date (or any date) as an NSDate without hours, minutes and seconds? ) to get rid of the hours.

Community
  • 1
  • 1
Jules
  • 7,568
  • 14
  • 102
  • 186
  • Please provide sample input and output so that we can see the problem for ourselves without having to type this up, build, and run. – Jeremy W. Sherman Apr 18 '11 at 22:01
  • It's better to paste the code itself rather than a picture of the code. – Caleb Apr 18 '11 at 22:35
  • 1
    Jules, what time zone are you in? Or what time zone is your system set to? Because, Xcode debugger will display the date/time in GMT+0 – Black Frog Apr 18 '11 at 22:45

2 Answers2

1

I actually see no connection between the midnightUTC method and your provided code.

Anyway, the problem with your given example is that, the parsing of the string 4/18/11 will default the missing values like minutes etc AND your current time zone, but the string will be assumed as GMT time so this will result in the offset you see.

The solution is to set the time zone for the NSDateFormatter. Look at this code, I've tested it a minute ago, and the console output. aaa reveals the odd offset, bbb does look as expected.

NSDateFormatter *dt = [[[NSDateFormatter alloc] init] autorelease];

[dt setDateStyle:NSDateFormatterShortStyle];

NSDate *aaa = [dt dateFromString:@"4/18/11"];

NSLog(@"1a. %@", [dt timeZone]);    
NSLog(@"1b. %@", aaa);

[dt setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *bbb = [dt dateFromString:@"4/18/11"];

NSLog(@"2a. %@", [dt timeZone]);        
NSLog(@"2b. %@", bbb);

Console output

1a. Europe/Berlin (CEST) offset 7200 (Daylight)
1b. 2011-04-17 22:00:00 +0000
2a. GMT (GMT+00:00) offset 0
2b. 2011-04-18 00:00:00 +0000
Nick Weaver
  • 47,228
  • 12
  • 98
  • 108
0

the midnightUTC function you're using creates dates by setting the timeZone to GMT, which is different from UTC half the year. UTC doesn't observe any summer / daylight savings time changes, while GMT does, so [NSTimeZone timeZoneForSecondsFromGMT:0] will be an hour off UTC for roughly half the year.

DJBHiney
  • 29
  • 2