timeIntervalSinceReferenceDate vs timeIntervalSince1970 vs timeIntervalSinceNow

use*_*656 8 ios swift swift2

我正在尝试NSDate在Swift 2中学习课程.

我发现每个NSDate对象都有三个属性,分别是:

  1. timeIntervalSinceReferenceDate
  2. timeIntervalSince1970
  3. timeIntervalSinceNow

对我来说有点困惑.我无法理解他们的解释,虽然我知道他们代表秒.

我做了这个代码:

let whatISThis = NSDate(timeIntervalSinceReferenceDate: NSTimeInterval(60))
Run Code Online (Sandbox Code Playgroud)

好的,我有约会,但那是什么?这三个属性有什么区别?

Wil*_*aan 33

timeIntervalSinceReferenceDate 是自2001年1月1日以来的秒数:凌晨12:00(深夜)

timeIntervalSince1970 是自1970年1月1日上午12:00(中午)以来的秒数

timeIntervalSinceNow 是从现在开始的秒数

我将列出这些例子:

let s0 = NSDate(timeIntervalSinceReferenceDate: NSTimeInterval(0)) // it means give me the time that happens after January,1st, 2001, 12:00 am by zero seconds
print("\(s0)") //2001-01-01 00:00:00

let s60 = NSDate(timeIntervalSinceReferenceDate: NSTimeInterval(60)) //it means give me the time that happens after January, 1st, 2001, 12:00 am by **60 seconds**
print("\(s60)") //2001-01-01 00:01:00

let s2 = NSDate(timeIntervalSince1970: NSTimeInterval(0)) // it means give me the time that happens after January, 1st, 1970 12:00 am by **zero** seconds
print("\(s2)") //1970-01-01 00:00:00

let s3 = NSDate() // it means the current time
print("\(s3)")//2015-10-25 14:12:40

let s4 = NSDate(timeIntervalSinceNow: NSTimeInterval(60)) //it means one minute (60 seconds) after the current time
print("\(s4)") //2015-10-25 14:13:40

let s5 = NSDate(timeIntervalSinceNow: NSTimeInterval(-60)) // it means one minute (60 seconds) before the current time
print("\(s5)") //2015-10-25 14:11:40

let sd = NSDate(timeIntervalSinceReferenceDate: NSTimeInterval(60)) // it means one minute after the reference time (January, 1st, 1970: 12:00 am)
print("\(sd)") //2001-01-01 00:01:00
Run Code Online (Sandbox Code Playgroud)

当然,如果你有一个NSDate对象,你可以简单地采取所有这些属性......

let sNow = NSDate()
sNow.timeIntervalSinceReferenceDate
sNow.timeIntervalSinceNow
sNow.timeIntervalSince1970
Run Code Online (Sandbox Code Playgroud)


Dun*_*n C 7

威廉解释了初始化者之间的区别.(投票)

NSDate还具有一些属性,可让您询问日期以回溯时间间隔.我会在一分钟内谈论这些.

首先是一个小背景:timeIntervalSince1970timeIntervalSinceReferenceDate方法使用不同的"纪元日期",或者被认为是"零日期"的日期(数字值为零的日期).

timeIntervalSince1970使用UNIX中标准的纪元日期:格林威治标准时间1970年1月1日午夜.这也是互联网上日期的标准纪元日期.

timeIntervalSinceReferenceDate 使用Mac OS/iOS纪元日期:2001年1月1日午夜.您可以轻松计算这两个参考日期之间的恒定偏移量,并使用加/减来在它们之间进行转换.

除了你一直在讨论的init方法之外,NSDate还有一些属性可以提供一个值,该值是给定引用日期以来的秒数:

var timeIntervalSinceReferenceDate: NSTimeInterval
var timeIntervalSince1970: NSTimeInterval
Run Code Online (Sandbox Code Playgroud)

这很令人困惑,因为属性的名称和init方法的名称在Swift中看起来是相同的.在Objective-C中更清楚地命名了init方法:

+ (instancetype _Nonnull)dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)seconds

+ (instancetype _Nonnull)dateWithTimeIntervalSince1970:(NSTimeInterval)seconds
Run Code Online (Sandbox Code Playgroud)

通常我发现Swift的方法命名比Objective-C更清晰,但init方法可能是个例外.