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

时间:2017-10-14 12:20:22

标签: ios swift datetime timestamp dateformatter

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

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

这是我的代码试用版。

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

1 个答案:

答案 0 :(得分:1)

你的字符串中有两个时区,所以你需要删除最后一个时区并逃避格林威治标准时间&#39;在解析之前。另外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"