无法获得必要的日期

时间:2019-08-22 20:58:34

标签: swift date

我正在尝试获取以天为单位的日期之间的差异。将日期转换为所需格式时出现问题。

func daysBefore(_ date: String) -> Int {

    let currentDate = Date()
    let dateFormater = DateFormatter()

    dateFormater.dateFormat = "dd.mm.YYYY"

    guard let nextDate = dateFormater.date(from: date) else {
        return 0
    }

    return currentDate.interval(ofComponent: .day, fromDate: nextDate)
}

extension Date {

    func interval(ofComponent comp: Calendar.Component, fromDate date: Date) -> Int {

        let currentCalendar = Calendar.current

        guard let start = currentCalendar.ordinality(of: comp, in: .era, for: date) else { return 0 }
        guard let end = currentCalendar.ordinality(of: comp, in: .era, for: self) else { return 0 }

        return end - start
    }
}

daysBefore("22.09.2019")

当我将日期从String转换为Date时:

    let currentDate = Date()
    let dateFormater = DateFormatter()

    dateFormater.dateFormat = "dd.mm.YYYY"

    guard let nextDate = dateFormater.date(from: date) else {
        return 0
    }

我总是得到类似:2018-12-22 21:09:00 +0000。

但预期(例如):22.09.2019。

0 个答案:

没有答案