Swift3 - 从数据库计算现在和日期之间的时差

Swift3 - Calculate time difference between now and date from Database

我想计算现在和数据库日期之间的时差。

"Fri Oct 13 2017 15:14:27 GMT+0200 (CEST)" 的正确 dateFormatter.dateFormat 是多少?

这是我的代码试用..

http://userguide.icu-project.org/formatparse/datetime

    let input = "Fri Oct 13 2017 15:14:27 GMT+0200 (CEST)"

    let dateFormatter = DateFormatter()
    var userCalendar = Calendar.current
    userCalendar.timeZone = TimeZone.current
    let requestedComponent: Set<Calendar.Component> = [.hour,.minute,.second]
    dateFormatter.dateFormat = "EEE MMM dd yyyy kk:mm:ss"
    let startTime = Date()
    let endTime = dateFormatter.date(from: input)
    let timeDifference = userCalendar.dateComponents(requestedComponent, from: endTime!, to: startTime)

    print(timeDifference)

    let date = Calendar(identifier: .gregorian).date(from: timeDifference)
    dateFormatter.dateFormat = "HH:mm:ss"
    let dateString =  dateFormatter.string(from: date!)

    print(dateString)

适用于:

dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss"
let endTime = dateFormatter.date(from: "14/10/17 11:00:00")

您的字符串中有两个时区,因此您需要删除最后一个时区并在解析之前转义 'GMT'。另外 kk 它用于从 01 到 24 的小时,你想要的是 00-23 在这种情况下你需要使用 HH:

let input = "Fri Oct 13 2017 15:14:27 GMT+0200 (CEST)"
let dateString = input.components(separatedBy: " ").dropLast().joined(separator: " ")
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z"
let date = dateFormatter.date(from: dateString)

要显示经过的时间,您可以使用 DateComponentsFormatter 并使用 unitsStyle .positional:

let elapsedTime = Date().timeIntervalSince(date)
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.unitsStyle = .positional
dateComponentsFormatter.string(from: elapsedTime)   // "23:32:34"