Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top