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

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

    If someone needs to display all time units e.g "hours minutes seconds" not just "hours". Let's say the time difference between two dates is 1hour 59minutes 20seconds. This function will display "1h 59m 20s".

    Here is my Objective-C code:

    extension NSDate {
    
        func offsetFrom(date: NSDate) -> String {
    
            let dayHourMinuteSecond: NSCalendarUnit = [.Day, .Hour, .Minute, .Second]
            let difference = NSCalendar.currentCalendar().components(dayHourMinuteSecond, fromDate: date, toDate: self, options: [])
    
            let seconds = "\(difference.second)s"
            let minutes = "\(difference.minute)m" + " " + seconds
            let hours = "\(difference.hour)h" + " " + minutes
            let days = "\(difference.day)d" + " " + hours
    
            if difference.day    > 0 { return days }
            if difference.hour   > 0 { return hours }
            if difference.minute > 0 { return minutes }
            if difference.second > 0 { return seconds }
            return ""
        }
    
    }
    

    In Swift 3+:

    extension Date {
    
        func offsetFrom(date: Date) -> String {
    
            let dayHourMinuteSecond: Set = [.day, .hour, .minute, .second]
            let difference = NSCalendar.current.dateComponents(dayHourMinuteSecond, from: date, to: self)
    
            let seconds = "\(difference.second ?? 0)s"
            let minutes = "\(difference.minute ?? 0)m" + " " + seconds
            let hours = "\(difference.hour ?? 0)h" + " " + minutes
            let days = "\(difference.day ?? 0)d" + " " + hours
    
            if let day = difference.day, day          > 0 { return days }
            if let hour = difference.hour, hour       > 0 { return hours }
            if let minute = difference.minute, minute > 0 { return minutes }
            if let second = difference.second, second > 0 { return seconds }
            return ""
        }
    
    }
    

提交回复
热议问题