Question

I know that this question was asked a million times, I just can't find a solution. The problem is: I'm modifying an NSDate to return either the date of the first day in the current month or the date of the first day in the next month. It seems to be working fine except for 1 thing: it gives back the time minus 2 or 3 hours.

Code:

NSCalendar *theCalendar = [NSCalendar currentCalendar];
int comp = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *theComp = [theCalendar components:comp fromDate:date];
[theComp setTimeZone:[NSTimeZone systemTimeZone]];
switch (roundingMode) {
    case FIRST_OF_MONTH:
        [theComp setDay:1];
        return [theCalendar dateFromComponents:theComp];
    case FIRST_OF_NEXT_MONTH:
        [theComp setMonth:theComp.month+1];
        [theComp setDay:1];
        return [theCalendar dateFromComponents:theComp];
}

Here's the debugger(gdb) output:

(gdb) po theComp
<NSDateComponents: 0x6e26170>
  TimeZone: Europe/Kiev (EET) offset 7200
  Calendar Year: 2012
  Month: 3
  Day: 1
(gdb) po date
2012-03-12 13:05:22 +0000
(gdb) po [theCalendar dateFromComponents:theComp]
2012-02-29 22:00:00 +0000

Any help would be greatly appreciated.

Thank you.

Was it helpful?

Solution

The date is displayed in GMT: 2012-02-29 00:00:00 +0000 is 2012-03-01 22:00:00 +0200. Also don't forget daylight saving time change which explains why you get a difference of 3 hours sometimes.

The result date is correct, but the debugger displays it in GMT.

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