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

前端 未结 19 2326
时光说笑
时光说笑 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:01

    If your purpose is to get the exact day number between two dates, you can work around this issue like this:

    // Assuming that firstDate and secondDate are defined
    // ...
    
    var calendar: NSCalendar = NSCalendar.currentCalendar()
    
    // Replace the hour (time) of both dates with 00:00
    let date1 = calendar.startOfDayForDate(firstDate)
    let date2 = calendar.startOfDayForDate(secondDate)
    
    let flags = NSCalendarUnit.DayCalendarUnit
    let components = calendar.components(flags, fromDate: date1, toDate: date2, options: nil)
    
    components.day  // This will return the number of day(s) between dates
    

提交回复
热议问题