我如何比较 Swift 3 中的两个日期 (NSDate) 并得到它们之间的天数?

How can i compare two dates (NSDate) in Swift 3 and get the days between them?

如何比较 Swift 3 中的两个日期? 我找到了许多其他 Swift 版本的解决方案,但它们对我不起作用。

let clickedDay:String = currentcell.DayLabel.text!
    let currentDate = NSDate()
    let currentDay = "" //want the current day
    let dateFormatter = DateFormatter()        
    var dateAsString = ""        
    if Int(clickedDay)! < 10 {            
        dateAsString = "0" + clickedDay + "-11-2016 GMT"
    }
    else {            
        dateAsString = clickedDay + "-11-2016 GMT"
    }

    dateFormatter.dateFormat = "dd-MM-yyyy zzz"
    let clickedDate = dateFormatter.date(from: dateAsString)        
    if currentDate as Date >= clickedDate! as Date {

        return true
    }
    else {
        //Want to get the days between the currentDate and clickedDate
        let daysLeft = ""
    }

我比较了两个日期,但我想要两个日期之间的天数。 有人可以帮我吗? 感谢和问候

添加: 如果我有日期 22.11.2016 和当前日期(现在是 18.11.2016)我想要那之间的天数(在本例中为 4)

尝试:

let days=Calendar.current.dateComponents([.day], from: date_1, to: date_2)
let nb_days=days.day

使用此函数获取两个日期之间的所有中间日期,只需检查下一个日期(最终日期)是否大于上一个日期(第一个日期)则顺序为 +1,否则顺序为 -1 :-

func selectDates(from upDate : Date, to downDate : Date, order : Int){
        var selectDate = Calendar.current.date(byAdding: .day, value: order, to: upDate)!
        while compareDate(dateInitial: selectDate, dateFinal: downDate) != true{
            print(" intermediate date is \(selectDate)")
            selectDate = Calendar.current.date(byAdding: .day, value: order, to: selectDate)!
        }
        print("*** intermediate dates are selected ***")

    }


func compareDate(dateInitial:Date, dateFinal:Date) -> Bool {
        let order = Calendar.current.compare(dateInitial, to: dateFinal, toGranularity: .day)
        switch order {
        case .orderedSame:
            return true
        default:
            return false
        }
    }

试试这个

let startDateComparisionResult:ComparisonResult = currentDate.compare(clickedDate! as NSDate)

if startDateComparisionResult == ComparisonResult.orderedAscending
{
    // Current date is smaller than end date.
}
else if startDateComparisionResult == ComparisonResult.orderedDescending
{
    // Current date is greater than end date.
}
else if startDateComparisionResult == ComparisonResult.orderedSame
{
    // Current date and end date are same
}

像这样简单地扩展 Date 并获得天数差异。

extension Date {
    func daysBetweenDate(toDate: Date) -> Int {
        let components = Calendar.current.dateComponents([.day], from: self, to: toDate)
        return components.day ?? 0
    }
}

现在像这样使用这个扩展

let numOfDays = fromDate.daysBetweenDate(toDate: toDate)

您可以像这样使用 DateFormatter 将 String 转换为 Date。

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
let date = dateFormatter.date(from: "18-11-2016")