简体   繁体   English

在 Swift 中查找 2 个日期之间的差异

[英]Finding the difference between 2 dates in Swift

I'm wondering if there's a way to compare two dates in Swift.我想知道是否有办法比较 Swift 中的两个日期。 I'm using dates to keep track of my timer when the app goes into the background, and also to track when people use a certain feature of my app.当应用程序进入后台时,我使用日期来跟踪我的计时器,并跟踪人们何时使用我的应用程序的某个功能。 I'm currently using two Date() variables and use math to compare the two calendar.DateComponents() of the two dates.我目前正在使用两个Date()变量并使用数学来比较两个日期的两个calendar.DateComponents() I'm sure Swift must have an easier way to get the difference between two DateComponents , but I don't know how to do this.我确信 Swift 必须有一种更简单的方法来获得两个DateComponents之间的差异,但我不知道该怎么做。 I would like to get the difference between the two dates in seconds.我想以秒为单位获得两个日期之间的差异。 I'm using XCode 11.4, Swift 5. Thanks!我正在使用 XCode 11.4、Swift 5。谢谢!

You don't need DateComponents then.那你就不需要DateComponents Date has a distance(to:) method that returns the difference in seconds: Date有一个distance(to:)方法,以秒为单位返回差异:

let diff = someDate.distance(to: anotherDate)

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

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