【问题标题】:getting a NSDate from NSCalendar and NSDateComponents从 NSCalendar 和 NSDateComponents 获取 NSDate
【发布时间】:2012-02-01 04:36:54
【问题描述】:

我的代码如下所示

NSDateComponents *components = [[NSDateComponents alloc] init];
components.year = [aDay.year intValue];   // 2012
components.month = [aDay.month intValue]; // 2
components.day = [aDay.day intValue];  // 1
components.hour = components.minute = components.second = 0;
NSDate *now = [self.calender dateFromComponents:components];

关于self.calendar,我尝试了两种方法:

self.calendar = [NSCalendar currentCalendar];
self.calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

但在此之后,当我打印“现在”日期时,总是这样:

(gdb) po now
2012-01-31 16:00:00 +0000

“现在”的日期应该是 2012-02-01 00:00:00

显然有 8 小时的时差,我现在在中国,所以我猜是 +0800 时区?

我该如何解决这个问题?我必须处理时区吗?

非常感谢!

【问题讨论】:

    标签: timezone nsdate nscalendar nsdatecomponents


    【解决方案1】:

    好吧,您为什么不尝试将时区设置为您喜欢的时区:

    NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"PST"];
    [calendar setTimeZone:zone];
    

    您可以通过以下方式查看已知时区列表:

    NSArray *timezones = [NSTimeZone knownTimeZoneNames];
    NSLog(@"%@", timezones);
    

    【讨论】:

    • 谢谢!那么问题仍然与时区有关吗?有什么方法可以直接获取用户当前的时区吗?就像 [NSCalendar currentCalendar]?
    • 我已经检查了默认时区,它是默认的亚洲/河滨,所以......我该怎么办。?
    【解决方案2】:

    我已经想通了。

    显示的是正确的,因为 NSDate 保存了绝对时间,所以时区总是 +0000,

    最好保持这种方式,因为我需要比较:NSDate等中的方法

    唯一的区别是当您要将绝对日期转换为用户可以读取的本地日期字符串时,请注意它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多