1

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

“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")
4

1 回答 1

1

您的字符串中有两个时区,因此您需要删除最后一个并在解析之前转义“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"
于 2017-10-14T12:37:49.913 回答