Swift:NSDate在几小时内减去NSDate

时间:2016-02-01 03:37:39

标签: swift nsdate

我在Swift中有一个名为// Changes Bar Color // UINavigationBar.appearance().barTintColor = UIColor.blueColor() // Changes Bar Button Color // UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UINavigationBar.classForCoder()]).tintColor = UIColor.whiteColor() // Set Up & Show ActivityController // let activityController = UIActivityViewController(activityItems: ["YOUR TEXT HERE"], applicationActivities: nil) self.presentViewController(activityController, animated: true, completion: nil) 的{​​{1}}字段的模型,我希望根据当前日期在到期前计算剩余小时数

使用现有的NSDate功能有一种简单的方法吗?

2 个答案:

答案 0 :(得分:2)

只需查找两个日期(“现在”和您的到期日期)之间的秒数(NSTimeInterval)并除以60 * 60 = 3600:

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

let hoursUntilExpiration = secondsUntilExpiration / 3600

例如:

  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.

答案 1 :(得分:2)

现在无法检查,但应该是

expirationDate.timeIntervalSinceNow / 3600