web-dev-qa-db-ja.com

Swift 3の2つの日付(NSDate)を比較して、それらの間の日数を取得するにはどうすればよいですか?

Swift 3の2つの日付を比較するにはどうすればよいですか?他の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 = ""
    }

2つの日付を比較しますが、その2つの日付の間にある日が必要です。誰かが私を助けてくれますか?感謝と挨拶

追加:2016年11月22日の日付と現在の日付(現在は2016年11月18日)がある場合、その間の日数(この場合は4)が必要です。

7
moxmlb

このように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を使用して、このように文字列を日付に変換できます。

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

これを試してください

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
Sapana Ranipa

この関数を使用して、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
Himanshu

試してみてください:

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