Swift 3 - find number of calendar days between two dates

前端 未结 11 2049
别跟我提以往
别跟我提以往 2020-12-12 23:51

The way I did this in Swift 2.3 was:

let currentDate         = NSDate()
let currentCalendar     = NSCalendar.currentCalendar()

var startDate : NSDate?
var e         


        
11条回答
  •  天命终不由人
    2020-12-13 00:25

    private func days(actual day1:[Int],expect day2:[Int]) -> Int {
    
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
    
            let first = "\(day1[2])-\(day1[1])-\(day1[0])"
            let firstDate = dateFormatter.date(from:first)!
            let last = "\(day2[2])-\(day2[1])-\(day2[0])"
            let lastDate = dateFormatter.date(from:last)!
    
            let currentCalendar = NSCalendar.current
    
            let components = currentCalendar.dateComponents([.day], from: firstDate, to: lastDate)
    
            return components.day!
        }
    

    Another approach to compare with components of day month year

    Usage:

    Input the dates in following format

    [dd, mm, yyyy]
    [9, 6, 2017]
    [6, 6, 2017]
    

提交回复
热议问题