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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40674599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:35:56  来源:igfitidea点击:

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

swiftxcodeswift3nsdatedate-comparison

提问by moxmlb

How can I compare two dates in Swift 3? I found many solutions for other Swift versions, but they doesn't work for me.

如何比较 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 = ""
    }

I compare the tow dates, but i want the days which are between that tow dates. Can someone help me pls? Thanks and greets

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

Added: If I have the date 22.11.2016 and the currentdate (now 18.11.2016) i want the days between that (in this case 4)

添加:如果我有日期 22.11.2016 和当前日期(现在是 18.11.2016),我想要这两者之间的天数(在这种情况下为 4)

回答by Nirav D

Simply make extension of Datelike this and get difference in days.

只需Date像这样进行扩展即可获得不同的天数。

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

Now use this extension like this

现在像这样使用这个扩展

let numOfDays = fromDate.daysBetweenDate(toDate: toDate)

You can use DateFormatterto convert String to Date like this.

您可以DateFormatter像这样将字符串转换为日期。

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

回答by Sapana Ranipa

Try This One

试试这个

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
}

回答by Himanshu

Use this function to get all intermediate dates between two dates, just check if down date (final date) is greater than up date (first date) then order is +1, else order -1 :-

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

回答by Marie Dm

Try:

尝试:

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