Swift 3 - find number of calendar days between two dates

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

    In Swift4 we can easily get no of days between two different calendar dates using below codes.

    First one is the difference in days with the current date.

    let previousDate = "2017-03-01"
    let currentDate = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let previousDateFormated : Date? = dateFormatter.date(from: previousDate)
    let difference = currentDate.timeIntervalSince(previousDateFormated!)
    var differenceInDays = Int(difference/(60 * 60 * 24 ))
    print(differenceInDays)
    

    Continuing with the above code ... Below is for finding no of days for two different dates. the content of previous date is taken from above date

    let futureDate = "2017-12-30"
    let futureDateFormatted : Date? = dateFormatter.date(from: futureDate)
    differenceInDays = (futureDateFormatted?.timeIntervalSince(previousDateFormated!))! / (60 * 60 * 24)
    
    print(differenceInDays)
    

提交回复
热议问题