Get difference between two dates in hour minutes – swift

If you are looking for difference between two dates in respect of days, hours, minutes etc., then instead of using timeinterval and calculating days, hours from those seconds. One can use Calendar inbuilt functions to get time difference between two dates as per days, hours, minutes. This can be done using date-components of calendar API in Foundation framework of iOS SDK in swift.

How to get date-components from date in swift

For this let us consider an example that we are creating a poll and showing user that this poll will end in this much of time from now.

    func getPollWillEndInInterval(havingEndDate endDate:Date) -> String {
        
        let interval = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date(), to: endDate)
        
        if let year = interval.year, year > 0 {
            if year == 1 {
                return "\(year) year"
            }
            return "\(year) years"
        } else if let month = interval.month, month > 0 {
            if month == 1 {
                return "a month"
            }
            return "\(month) months"
            
        } else if let day = interval.day, day > 0 {
            var doWeHaveNextDaysHoursMinutes = false
            if let hour = interval.hour, hour > 0 {
                doWeHaveNextDaysHoursMinutes = true
            }
            if let minute = interval.minute, minute > 0 {
                doWeHaveNextDaysHoursMinutes = true
            }
            var totalDay = day
            if doWeHaveNextDaysHoursMinutes {
                totalDay = totalDay + 1
            }
            if totalDay == 1 {
                return "\(totalDay) day"
            }
             return "\(totalDay) days"
            
        } else if let hour = interval.hour, hour > 0 {
            if hour == 1 {
                return "\(hour) hour"
            }
            return "\(hour) hours"
        } else if let minute = interval.minute, minute > 0 {
            if minute > 1 {
                return "\(minute) minute"
            }
            return "\(minute) mins"
        } else if let seconds = interval.second, seconds > 0 {
            return "\(seconds) seconds"
        }  else {
            
            return "a few seconds"
        }
    }

In above function, we will pass the date on which poll is being getting ended. We are getting date-compnents between two dates using calendar API in swift. In component list we are passing, required components unit to be passed. For example, if we need only minutes then we will only pass minute component only in above date component.

Note:- In above code for example if, we are getting difference between dates having time then it will gives us 2 days 12 hours 30 minutes 30 seconds. So as we want to consider the remaining hours as a day that’s why we are adding a day in above code snippet.