在swift 3中获得两次时间差

Tor*_*oco 7 nstimeinterval swift3

我有2个变量,我从datePicker获得2次,我需要在变量上保存它们之间的差异.

    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "HHmm"

    time2 = timeFormatter.date(from: timeFormatter.string(from: datePicker.date))!
Run Code Online (Sandbox Code Playgroud)

我试图从他们两个得到timeIntervalSince1970并且他们减去它们并得到毫秒的差异,我将回到小时和分钟,但是我得到一个非常大的数字,它与实际时间不对应.

let dateTest = time2.timeIntervalSince1970 - time1.timeIntervalSince1970
Run Code Online (Sandbox Code Playgroud)

然后我尝试使用time2.timeIntervalSince(date:time1),但结果毫秒再次远远超过实际时间.

我怎样才能得到2次正确的时差,并以8小时23分钟的格式"0823"得到小时和分钟的结果?

vad*_*ian 15

任何日期数学的推荐方法是CalendarDateComponents

let difference = Calendar.current.dateComponents([.hour, .minute], from: time1, to: time2)
let formattedString = String(format: "%02ld%02ld", difference.hour!, difference.minute!)
print(formattedString)
Run Code Online (Sandbox Code Playgroud)

格式%02ld添加填充零.

如果您需要一个标准格式,在小时和分钟之间使用冒号DateComponentsFormatter()可能是一种更方便的方式

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
print(formatter.string(from: time1, to: time2)!)
Run Code Online (Sandbox Code Playgroud)


Ger*_*eon 10

TimeInterval 测量秒,而不是毫秒:

let date1 = Date()
let date2 = Date(timeIntervalSinceNow: 12600) // 3:30

let diff = Int(date2.timeIntervalSince1970 - date1.timeIntervalSince1970)

let hours = diff / 3600
let minutes = (diff - hours * 3600) / 60
Run Code Online (Sandbox Code Playgroud)


小智 8

要获得两个时间间隔之间的持续时间(以秒为单位),可以使用 -

let time1 = Date(timeIntervalSince1970: startTime)
let time2 = Date(timeIntervalSince1970: endTime)
let difference = Calendar.current.dateComponents([.second], from: time1, to: time2)
let duration = difference.second
Run Code Online (Sandbox Code Playgroud)


car*_*ary 7

现在你可以通过这种方式在 swift 5 中做到这一点,

func getDateDiff(start: Date, end: Date) -> Int  {
    let calendar = Calendar.current
    let dateComponents = calendar.dateComponents([Calendar.Component.second], from: start, to: end)

    let seconds = dateComponents.second
    return Int(seconds!)
}
Run Code Online (Sandbox Code Playgroud)

  • 我必须在这里导入哪个模块?我总是收到错误``使用未声明的类型'秒'``` (4认同)