简体   繁体   English

比较 Swift 中的两个日期

[英]Compare two dates in Swift

So I have to save my cache with the timestamp(named timestamp1) The next time app loads, I have to compare the difference with the current timestamp and timestamp1.所以我必须用时间戳保存我的缓存(名为timestamp1) 下次应用加载时,我必须比较当前时间戳和时间戳1的差异。

How will I implement this?我将如何实施?

You can directly access it through property timeIntervalSinceNow of Date .您可以通过Date属性timeIntervalSinceNow直接访问它。 Also, there is no need to use NSDate in Swift 3. Use Date and date(from:) method of DateFormatter return instance of Date?另外,Swift 3 中不需要使用NSDate 。使用DateFormatter Datedate(from:)方法返回Date?实例Date? not NSDate?不是NSDate? . .

let timeInterval = date.timeIntervalSinceNow

And you can get TimeInterval between two dates using method timeIntervalSince(_:) .您可以使用timeIntervalSince(_:)方法获取两个日期之间的TimeInterval

let timeInterval = date1.timeIntervalSince(date2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM