rigdonmr
rigdonmr

Reputation: 2702

Swift: NSDate minus NSDate in hours

I have a model in Swift with an NSDate field named expirationDate and I want to calculate the hours remaining before expiration based on the current date.

Is there an easy way to do this with existing NSDate functionality?

Upvotes: 1

Views: 415

Answers (2)

Undo
Undo

Reputation: 25697

Just find the number of seconds (NSTimeInterval) between the two dates ('now' and your expiration date) and divide by 60*60 = 3600:

let secondsUntilExpiration = expirationDate.timeIntervalSinceDate(NSDate());

let hoursUntilExpiration = secondsUntilExpiration / 3600

For example:

  7> let now = NSDate() 
now: NSDate = 2016-02-01 03:44:06 UTC
  8> let expirationDate = now.dateByAddingTimeInterval(60*60*10) // ten hours from now
expirationDate: NSDate = 2016-02-01 13:44:06 UTC
  9> let secondsUntilExpiration = expirationDate.timeIntervalSinceDate(NSDate()); 
secondsUntilExpiration: NSTimeInterval = 35991.422316968441
 10> let hoursUntilExpiration = secondsUntilExpiration / 3600 
hoursUntilExpiration: Double = 9.9976173102690122 
// Slightly less than the 10 hours above because of the time it took me to type.

Upvotes: 2

Amadan
Amadan

Reputation: 198324

Can't check now, but should be something like

expirationDate.timeIntervalSinceNow / 3600

Upvotes: 2

Related Questions