NSDate和NSDateComponents返回错误的日期 [英] NSDate and NSDateComponents return wrong date

查看:89
本文介绍了NSDate和NSDateComponents返回错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题被问过一百万次,我找不到解决办法。问题是:我正在修改 NSDate ,以返回当月第一天的日期或下个月第一天的日期。它似乎工作正常,除了一件事:它给予时间减去2或3小时。

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.

代码:

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];
}

这是调试器(gdb)输出:

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

非常感谢任何帮助。

谢谢。

推荐答案

日期以格林威治标准时间显示: 2012-02-29 00:00:00 +0000 2012-03-01 22:00:00 +0200 。另外,请不要忘记夏令时变化,这解释了为什么有时会有3个小时的差异。

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.

结果日期是正确的,但调试器在GMT中显示它。

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

这篇关于NSDate和NSDateComponents返回错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆