Swift 3 - find number of calendar days between two dates

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

    Swift 4 Version

    let startDate = "2000-11-22"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let formatedStartDate = dateFormatter.date(from: startDate)
    let currentDate = Date()
    let components = Set([.second, .minute, .hour, .day, .month, .year])
    let differenceOfDate = Calendar.current.dateComponents(components, from: formatedStartDate!, to: currentDate)
    
    print (differenceOfDate)
    

    Printed - year: 16 month: 10 day: 19 hour: 12 minute: 16 second: 42 isLeapMonth: false

    swift4 calendar date

提交回复
热议问题