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

前端 未结 19 2058
时光说笑
时光说笑 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 02:49

    You ask:

    I'd like to have a function that compares the two dates and if(seconds > 60) then it returns minutes, if(minutes > 60) return hours and if(hours > 24) return days and so on.

    I'm assuming that you're trying to build a string representation of the elapsed time between two dates. Rather than writing your own code to do that, Apple already has a class designed to do precisely that. Namely, use DateComponentsFormatter, set allowedUnits to whatever values make sense to your app, set unitsStyle to whatever you want (e.g. .full), and then call string(from:to:).

    E.g. in Swift 3:

    let previousDate = ...
    let now = Date()
    
    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .full
    formatter.allowedUnits = [.month, .day, .hour, .minute, .second]
    formatter.maximumUnitCount = 2   // often, you don't care about seconds if the elapsed time is in months, so you'll set max unit to whatever is appropriate in your case
    
    let string = formatter.string(from: previousDate, to: now)
    

    This also will localize the string appropriate for the device in question.

    Or, in Swift 2.3:

    let previousDate = ...
    let now = NSDate()
    
    let formatter = NSDateComponentsFormatter()
    formatter.unitsStyle = .Full
    formatter.allowedUnits = [.Month, .Day, .Hour, .Minute, .Second]
    formatter.maximumUnitCount = 2
    
    let string = formatter.stringFromDate(previousDate, toDate: now)
    

    If you're looking for the actual numeric values, just use dateComponents. E.g. in Swift 3:

    let components = Calendar.current.dateComponents([.month, .day, .hour, .minute, .second], from: previousDate, to: now)
    

    Or, in Swift 2.3:

    let components = NSCalendar.currentCalendar().components([.Month, .Day, .Hour, .Minute, .Second], fromDate: previousDate, toDate: now, options: [])
    

提交回复
热议问题