【问题标题】:Incorrect date formatting?日期格式不正确?
【发布时间】:2015-01-15 12:22:33
【问题描述】:

请帮助我处理不明显的代码行为

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.hour     = 15;
dateComponents.minute   = 20;
dateComponents.calendar = calendar;

NSDate * endDate    = [calendar dateFromComponents:dateComponents];

结束日期是 0001-01-01 12:49:43 +0000。为什么?

由于时区不同,小时值可能不正确。为什么会有如此奇怪的分秒值? 问候。

【问题讨论】:

  • 如果我不得不猜测,我会说这是由于自 01/01/0001 以来您的日历中累积的闰秒造成的,所以我会尝试设置年份。但我只是编造的,所以这可能是完全错误的。
  • 有趣……你能打印出日历的时区属性吗? secondsFromGMTabbreviation.
  • @GuillaumeAlgis 好主意!
  • 关于我之前的评论,将年份设置为 2015 年对我来说确实有效,我的时区会花费或花费几个小时。
  • 请注意,规范说:“当提供的组件不足以完全指定绝对时间时,日历会使用其选择的默认值。”因此,“奇怪”的秒值至少并不出人意料。而且,虽然 NSDate 方案没有考虑闰秒,但几个世纪以来时区方案已经改变了好几次;特别是从“当地中午”时间切换到时区。

标签: objective-c nsdate nsdatecomponents


【解决方案1】:

如果我们只是考虑下面的代码sn-p

NSCalendar *calendar = [NSCalendar currentCalendar];        
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setCalendar:calendar];
NSDate *date = [calendar dateFromComponents:components]; 

date = 0000-12-31 23:06:32 +0000,因为:

日历将有关计算时间系统的信息封装在 其中定义了一年的开始、长度和划分。

[...]

当提供的组件不足以完全指定绝对时间时,日历会使用其选择的默认值。 Apple Documentation

NSDateComponents 对象本身没有意义;您需要知道它是根据什么日历解释的,并且您需要知道这些值是单位的绝对值还是单位的数量。 Apple Documentation

实际上,一切都很好,正如文档所说的那样。

【讨论】:

  • 我们阅读了文档,但对其工作原理存在疑问。谢谢。
猜你喜欢
  • 2020-05-31
  • 1970-01-01
  • 2018-04-20
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多