Swift 3 - find number of calendar days between two dates

前端 未结 11 2028
别跟我提以往
别跟我提以往 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:19

    Updated for Swift 3:

    if you want to print the number of days as well as days list between two calendar dates, used below simple code;

    // Variable Declaration:

    var daysListArray = [String]()
    

    // function Defination:

    func printCountBtnTwoDates(mStartDate: Date, mEndDate: Date) -> Int {
        let calendar = Calendar.current
        let formatter = DateFormatter()
        var newDate = mStartDate
        daysListArray.removeAll()
    
        while newDate <= mEndDate {
            formatter.dateFormat = "yyyy-MM-dd"
            daysListArray.append(formatter.string(from: newDate))
            newDate = calendar.date(byAdding: .day, value: 1, to: newDate)!
        }
       // print("daysListArray: \(daysListArray)") // if you want to print list between start date and end date
        return daysListArray.count
    }
    

    // To call above function:

        let count = self.printCountBtnTwoDates(mStartDate: your_start_date, mEndDate: your_end_date)
        print("count: \(count)") // date count
    

    // Enjoy coding...!

提交回复
热议问题