user2228656 user2228656 - 5 months ago 45
Swift Question

timeIntervalSinceReferenceDate vs timeIntervalSince1970 vs timeIntervalSinceNow

I am trying to study

NSDate
class in Swift 2.

I found that each NSDate object has three properties, which are:


  1. timeIntervalSinceReferenceDate

  2. timeIntervalSince1970

  3. timeIntervalSinceNow



A little bit confusing for me. I couldn't understand the interpretation of them though I know they represents the seconds.

I did this code:

let whatISThis = NSDate(timeIntervalSinceReferenceDate: NSTimeInterval(60))


Okay I got a date, but what is that? what is the difference between those three properties?

Answer

timeIntervalSinceReferenceDate is the number of seconds since January, 1st, 2001: 12:00 am (mid night)

timeIntervalSince1970 is the number of seconds since January, 1st, 1970, 12:00 am (mid night)

timeIntervalSinceNow is the number of seconds since now

I will list these examples:

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

And of course if you have a NSDate objects, you can take all these properties simply ...

let sNow = NSDate()
sNow.timeIntervalSinceReferenceDate
sNow.timeIntervalSinceNow
sNow.timeIntervalSince1970
Comments