-1

I have a date.

NSLog shows it as:

2014-05-11 21:59:59 +0000

Now I want to get the same date but with hour, minutes and seconds set to zero:

2014-05-11 00:00:00 +0000

My code:

    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setTimeZone:[NSTimeZone localTimeZone]];
    NSDateComponents *components = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:dayOfWeek];
    NSLog(@"components: %@", components);

    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:[components year]];
    [comps setMonth:[components month]];
    [comps setDay:[components day]];
    [comps setHour:0];
    [comps setMinute:0];
    [comps setSecond:0];
    NSLog(@"New date: %@", [calendar dateFromComponents:comps]);

But NSLog shows:

2014-05-10 22:00:00 +0000

Seems the day and hour is calculated wrong. Note, that I am in Germany, but I use [NSTimeZone localTimeZone] because I assume this should return the correct timezone?

chancyWu
  • 14,073
  • 11
  • 62
  • 81
mrd
  • 4,561
  • 10
  • 54
  • 92
  • Look at the "+0000" at the end of the NSLog. You're setting the date in Germany (+0200) and then logging it in UTC (+0000) so it's going to be 2 hours off. – Stonz2 May 06 '14 at 16:00
  • possible duplicate of [Creating NSDate from NSDateComponents off by one day](http://stackoverflow.com/questions/7318249/creating-nsdate-from-nsdatecomponents-off-by-one-day), [Issue with NSDate from NSDateComponents](http://stackoverflow.com/questions/15307892/issue-with-nsdate-from-nsdatecomponents), and some others ... – Martin R May 06 '14 at 16:15
  • @Stonz2 does this mean I should NOT set the timezone? – mrd May 06 '14 at 16:24

1 Answers1

6

There isn't really a question... Still:

NSDate is always in UTC. When you call NSLog, it displays what time it would be in London with daylight savings time turned off. So your initial NSDate is one second before 10pm in London with daylight savings time turned off (UTC) and one second before midnight where you are. You then calculate an NSDate that is just at the start of your day in Germany. At that point in time, it's 10pm on the previous day in UTC, and that's what NSLog shows.

gnasher729
  • 51,477
  • 5
  • 75
  • 98