【问题标题】:Why am I getting wrong time output with correct timezone?为什么我在正确的时区得到错误的时间输出?
【发布时间】:2012-12-27 02:18:16
【问题描述】:

为什么我会得到这个输出时间:

2013-01-12 18:24:37.783 代码测试[10328:c07] 0001-01-01 17:12:52 +0000

当我运行这段代码时:

NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone localTimeZone];

NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:[NSDate date]];
components.hour   = 17;
components.minute = 47;
components.second = 0;

NSDate *fire = [calendar dateFromComponents:components];
NSLog(@"%@", fire);

我试过默认时区,系统时区。它总是给我不同的分钟和秒的输出!加上错误的日期 0001-01-01!!!!知道为什么吗?

附加测试:

运行此代码时:

NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone localTimeZone];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:[NSDate date]];
components.hour   = (components.hour + 1) % 24;
components.minute = 0;
components.second = 0;
NSDate *fire = [calendar dateFromComponents:components];
NSLog(@"%@", fire);

它给了我这个输出:

2013-01-12 18:41:41.552 代码测试[10648:c07] 0001-01-01 18:25:52 +0000

2013-01-12 18:42:16.274 代码测试[10648:c07] 0001-01-01 18:25:52 +0000

2013-01-12 18:42:30.310 代码测试[10648:c07] 0001-01-01 18:25:52 +0000

【问题讨论】:

  • 你能告诉我,你想表演什么,你的要求吗?
  • 现在触发通知..但这是我想知道的一般行为。

标签: ios objective-c xcode timezone output


【解决方案1】:

您缺少年、月和日组件。

做:

NSDateComponents *components = [calendar components:NSUIntegerMax fromDate:[NSDate date]];

现在应该给你正确的日期。

旁注:由于NSCalendarUnitNSUInteger 的位域类型定义,我传入NSUIntegerMax 以检索所有可能的日历单位。这样我就不必有大量的按位 OR 语句。

【讨论】:

  • NSUIntegerMax 的绝妙技巧,但由于 Whylonely 似乎是初学者,您可能应该解释一下。无论如何+1
  • 不过我不认为这是我的功劳,这是我在这里学到的一个技巧:)
  • @PeterWarbo 感谢您的聪明回答。 NSUIntegerMax 对我帮助很大。
  • 一直认为必须有比拥有超长按位or 语句更好的方法,NSUIntegerMax 的绝妙提示!
【解决方案2】:

您还需要使用calendar components: 方法请求年月日。

来自 Apple 文档:

NSDateComponents 的一个实例不负责回答 关于日期的问题超出了它的信息 初始化。

NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit fromDate:[NSDate date]];

日期的NSLog会以默认时区显示时间。

【讨论】:

    猜你喜欢
    • 2021-05-06
    • 2021-11-11
    • 2012-04-26
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 2020-10-11
    • 2020-03-13
    • 1970-01-01
    相关资源
    最近更新 更多