Question

My objective is to get a NSDate representing the same day as another NSDate, but with the hours, minutes, seconds, set to 0.

So 2013/11/27 13:23:32 would become 2013/11/27 00:00:00.

I made this function, for which I found examples on the internet

+ (NSDate*)dayEarliestDateForDate:(NSDate*)date {
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
    [comps setHour:0];
    [comps setMinute:0];
    [comps setSecond:0];
    NSDate* dateEarliest = [calendar dateFromComponents:comps];
    return dateEarliest;
}

But strangely, when I run it

NSDate* date2 = [NSDate dayEarliestDateForDate:date1];

I get this :

(lldb) po date1
$3 = 0x11d98dc0 2013-08-**13** 07:37:58 +0000
(lldb) po date2
$4 = 0x140588f0 2013-08-**12** 22:00:00 +0000

As you see, the day changed !

Any ideas ? Thank you

Was it helpful?

Solution

Ludovic, as the NSDate is a only "a moment in a timeline", when you do NSLog to a NSDate, it prints it with the timezone of Greenwich time (that is the +0000 after the time) - and as you didn't define any time zone to your NSDateComponents comps object, it just converted to a NSDate using GMT +0, and you are probably in a GMT +2 zone.

In order to fix this, I would suggest you to set the time zone of your NSDateComponents to object.

[comps setTimeZone:[NSTimeZone localTimeZone]];

or set the desired time zone, in case it's not the local.

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