Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

前端 未结 19 2328
时光说笑
时光说笑 2020-11-22 02:16

I am trying to get the difference between the current date as NSDate() and a date from a PHP time(); call for example: NSDate(timeIntervalSin

19条回答
  •  独厮守ぢ
    2020-11-22 03:03

    Slightly modified code for Swift 3.0

    let calendar = NSCalendar.current as NSCalendar
    
    // Replace the hour (time) of both dates with 00:00
    let date1 = calendar.startOfDay(for: startDateTime)
    let date2 = calendar.startOfDay(for: endDateTime)
    
    let flags = NSCalendar.Unit.day
    let components = calendar.components(flags, from: date1, to: date2, options: [])
    
    return components.day!
    

提交回复
热议问题