【问题标题】:initWithTimeIntervalSinceReferenceDate return null when the year is less than 2000initWithTimeIntervalSinceReferenceDate 在年份小于 2000 时返回 null
【发布时间】:2016-09-29 16:07:52
【问题描述】:

我在日期选择器中存储我的日期下方有此代码:

uint64_t offset = (uint64_t)[[self.dataPicker date] timeIntervalSinceReferenceDate];
// store this 64-bit unsigned integer.

NSLog(@"Offset -> %llu",offset);

要再次转换日期格式,我使用以下命令:

NSDate *data = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:offset];
NSLog(@"Before -> %@",data);

但是这段代码有一个问题,当我选择小于2000年(1999,1998,1997 ...)的年份时,命令initWithTimeIntervalSinceReferenceDate总是返回null,但是offset仍然是存储一个值。

发生了什么,我该如何解决这个问题?

【问题讨论】:

  • 我不确定,但这可能是一个提示:对于timeIntervalSinceReferenceDate,文档说:“如果日期对象早于系统的绝对参考日期(00 2001 年 1 月 1 日:00:00 UTC)。”而uint64_t 似乎很无符号,因此可能存在负值问题。我建议保存为NSTimeInterval(其中包含double 原语)。
  • 真的返回null吗?

标签: ios objective-c nsdate uidatepicker


【解决方案1】:

考虑以下事实:

  • 参考日期为 2001 年 1 月 1 日。
  • 该日期之前的所有时间间隔值都是负数。
  • 您使用的类型是uint64_t,它永远不会是负数。

有一个专用类型 NSTimeInterval(又名 double)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多