【问题标题】:Find difference between just the time of two dates in seconds以秒为单位查找两个日期的时间之间的差异
【发布时间】:2019-07-16 17:36:14
【问题描述】:

我有两个约会。我不关心日期部分,只关心时间。

如何比较 2 个日期并获取 2 个日期之间的时间间隔?

我应该将日期设置为 01-01-2000 并单独比较时间吗?

【问题讨论】:

标签: swift date nstimeinterval


【解决方案1】:

使用DateComponents 并获取两个日期的小时、分钟和秒。此时,您必须假设每天 24 小时 86400 秒。由于您正在进行与日期无关的计算,因此无需担心夏令时或闰秒或其他任何事情。

将两个日期的小时、分钟和秒转换为一天中的总秒数。然后只需将两个总数相减即可。

这是一个有用的日期扩展:

extension Date {
    func secondsSinceMidnight() -> TimeInterval {
        let comps = Calendar.current.dateComponents([.hour,.minute,.second], from: self)

        return TimeInterval(comps.hour! * 3600 + comps.minute! * 60 + comps.second!)
    }

    func timeDifference(to date: Date) -> TimeInterval {
        return date.secondsSinceMidnight() - self.secondsSinceMidnight()
    }
}

使用您的两个日期致电timeDifference(to:),忽略日期的日期部分,您将以秒为单位获得差异。

否定结果意味着to 日期更接近午夜。

【讨论】:

    【解决方案2】:

    这是完全基于DateComponents的rmaddy解决方案的替代方案

    extension Date {
        func timeComponents() -> DateComponents {
            return Calendar.current.dateComponents([.hour,.minute,.second], from: self)
        }
    
        func timeDifference(to date: Date) -> Int {
            return Calendar.current.dateComponents([.second], from: date.timeComponents(), to: self.timeComponents()).second!
        }
    }
    

    【讨论】:

      【解决方案3】:

      如果你有两个日期,你可以使用方法 timeIntervalSince(Date)。

      例如:

      func calculateElapsedTime(from someTime: Date) -> TimeInterval {
          
          let currentTime = Date()
          
          var elapsedTime = currentTime.timeIntervalSince(someTime)
          
          return elapsedTime
      
      }
      

      如果只想考虑两个日期之间的时间差,首先要对日期进行归一化。这可以通过以下繁琐的方式完成:

      let currentDate = Date()
      let anotherDate = Date(timeInterval: 60, since: currentDate)
      let formatter = DateFormatter()
      
      formatter.timeStyle = .short
      
      let currentTime = formatter.string(from: currentDate)
      let anotherTime = formatter.string(from: anotherDate)
      
      let currentIntervalTime = formatter.date(from: currentTime)
      let anotherIntervalTime = formatter.date(from: anotherTime)
      
      let elapsedTime = anotherIntervalTime?.timeIntervalSince(currentIntervalTime!)
      

      【讨论】:

      • 这不也是按日期计算的吗?例如,如果日期 1 是 06-15-2019 12:00:00 并且日期 2 是 06-14-2019 12:01:00 - 我正在寻找 60 的 timeInterval 的结果,因为它的 TIME 仅相差 1 分钟只要。有意义吗?
      • 这个方法计算整个时间。这意味着如果存在天差,则时间间隔为 24 小时(以秒为单位)。我理解你的问题,我无法判断它是否有意义。
      猜你喜欢
      • 2012-09-13
      • 1970-01-01
      • 2011-04-27
      • 2011-05-20
      • 1970-01-01
      • 2012-12-03
      • 2023-04-01
      • 1970-01-01
      • 2012-05-16
      相关资源
      最近更新 更多