简体   繁体   English

获取两个日期之间的差异

[英]Get difference between two dates

I need the difference between milliseconds and the date at the moment.我现在需要毫秒和日期之间的差异。 It needs to be formatted as HH:mm:ss and my code is not coming out with the correct difference.它需要格式化为 HH:mm:ss 并且我的代码没有出现正确的差异。

var differenceDate = NSDate(timeIntervalSince1970: Double(currentTimeInMiliseconds()))
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm:ss"
        self.callDetail.text = dateFormatter.string(from: differenceDate as Date)

 func currentTimeInMiliseconds() -> Int! {
        let date = NSDate()
        return Int(date.timeIntervalSince1970 * 1000)
    }

If you want the amount of time between two date objects in a HH:mm:ss format, you generally would use NSDateComponentsFormatter .如果您想要HH:mm:ss格式的两个日期对象之间的时间量,您通常会使用NSDateComponentsFormatter In Swift 3:在 Swift 3 中:

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.hour, .minute, .second]
formatter.zeroFormattingBehavior = .pad

let string = formatter.string(from: referenceDate, to: date)

In Swift 2:在 Swift 2 中:

let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Positional
formatter.allowedUnits = [.Hour, .Minute, .Second]
formatter.zeroFormattingBehavior = .Pad

let string = formatter.stringFromDate(referenceDate, toDate: date)

The problem is that differenceDate , despite the name, is not a date!问题是differenceDate ,尽管名称,不是日期! It's just a time interval — an abstract number of seconds.这只是一个时间间隔——抽象的秒数。 If you want to express it as hours and minutes and seconds, just keep dividing by 60 and taking the remainder.如果您想将其表示为小时、分钟和秒,只需继续除以 60 并取余数。 But bear in mind that those are not real hours and minutes and seconds.但请记住,这些不是真正的小时、分钟和秒。

Example:例子:

// make two dates, get the difference
let greg = Calendar(identifier: .gregorian)
let dc = DateComponents(calendar: greg, 
    year: 1954, month: 8, day: 10, hour: 3, minute: 0, second: 0)
let d1 = greg.date(from: dc)!
let d2 = Date()
let diff = d2.timeIntervalSince(d1)

// calculate hours, minutes, and seconds
var min = diff/60
let sec = diff.truncatingRemainder(dividingBy: 60)
let hr = min/60
min = min.truncatingRemainder(dividingBy: 60)

// format the output as a string
let nf = NumberFormatter()
nf.roundingMode = .floor
nf.minimumIntegerDigits = 2

let hrs = nf.string(from: hr as NSNumber)
let mins = nf.string(from: min as NSNumber)

nf.maximumFractionDigits = 3
let secs = nf.string(from: sec as NSNumber)

print(hrs! + ":" + mins! + ":" + secs!) // 545169:33:18.841

This gives you your desired formatting and your milliseconds.这为您提供了所需的格式和毫秒数。 You can do the same thing with DateComponentsFormatter, as suggested by Rob, but you'll get exactly the same calculated result.您可以按照 Rob 的建议对 DateComponentsFormatter 执行相同的操作,但您将获得完全相同的计算结果。

I found that the easiest way was to use NSCalendar我发现最简单的方法是使用 NSCalendar

let calendar: NSCalendar = NSCalendar.current as NSCalendar
        let date1 = call!.startTime.dateFromMilliseconds()
        let date2 = NSDate()
        let components = calendar.components([.hour, .second, .minute], from: date1 , to: date2 as Date, options: [])
        differenceDate =  NSCalendar(identifier: NSCalendar.Identifier.gregorian)?.date(from: components) as NSDate!

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

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