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

时间:2016-11-18 10:23:34

标签: swift xcode swift3 nsdate date-comparison

如何比较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)

4 个答案:

答案 0 :(得分:12)

只需像这样扩展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")

答案 1 :(得分:2)

使用此函数获取两个日期之间的所有中间日期,只检查下降日期(最终日期)是否大于上升日期(第一个日期),然后订单为+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
        }
    }

答案 2 :(得分:2)

试试这个

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
}

答案 3 :(得分:1)

尝试:

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