NSDate and NSDateComponents return wrong date

随声附和 提交于 2019-11-27 08:37:29

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/9668625/nsdate-and-nsdatecomponents-return-wrong-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!