Calculate Time Difference in Swift 4

Calculate time difference in Swift 4

First, your math is wrong. 10:30 -> 1:20 is actually 2 hr 50 min. Second, you need to specify AM or PM, or use a 24-hour (military-style) clock. Finally, the solution is to use DateFormatter to convert the strings into Date values and use those to get the time difference, which you can then convert into hours/minutes.

    let time1 = "10:30AM"
let time2 = "1:20PM"

let formatter = DateFormatter()
formatter.dateFormat = "h:mma"

let date1 = formatter.date(from: time1)!
let date2 = formatter.date(from: time2)!

let elapsedTime = date2.timeIntervalSince(date1)

// convert from seconds to hours, rounding down to the nearest hour
let hours = floor(elapsedTime / 60 / 60)

// we have to subtract the number of seconds in hours from minutes to get
// the remaining minutes, rounding down to the nearest minute (in case you
// want to get seconds down the road)
let minutes = floor((elapsedTime - (hours * 60 * 60)) / 60)

print("\(Int(hours)) hr and \(Int(minutes)) min")

How can I calculate Difference from two times in swift 3?

Use timeIntervalSince(_ anotherDate: Date) function to get difference between two dates.

func findDateDiff(time1Str: String, time2Str: String) -> String {
let timeformatter = DateFormatter()
timeformatter.dateFormat = "hh:mm a"

guard let time1 = timeformatter.date(from: time1Str),
let time2 = timeformatter.date(from: time2Str) else { return "" }

//You can directly use from here if you have two dates

let interval = time2.timeIntervalSince(time1)
let hour = interval / 3600;
let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
let intervalInt = Int(interval)
return "\(intervalInt < 0 ? "-" : "+") \(Int(hour)) Hours \(Int(minute)) Minutes"
}

Call the function with two times to find the difference.

let dateDiff = findDateDiff(time1Str: "09:54 AM", time2Str: "12:59 PM")
print(dateDiff)

How to get time difference between two times

To solve this you need to get familiar with TimeIntervals.

The probably easiest approach would be to get the timeIntervalSince1970, which is representing the amount of seconds since 01.01.1970 00:00..

After that you can simply substract: newDate.timeIntervalSince1970 - oldDate.timeIntervalSince1970

This gives you the seconds between these two dates. You can then convert the result into hours, days, etc.

let oldDate: Date = Your Old Date
let newDate: Date = Your New Date

let difference = newDate.timeIntervalSince1970 - oldDate.timeIntervalSince1970

Get time difference between two times in swift 3

The recommended way to do any date math is Calendar and DateComponents

let difference = Calendar.current.dateComponents([.hour, .minute], from: time1, to: time2)
let formattedString = String(format: "%02ld%02ld", difference.hour!, difference.minute!)
print(formattedString)

The format %02ld adds the padding zero.

If you need a standard format with a colon between hours and minutes DateComponentsFormatter() could be a more convenient way

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
print(formatter.string(from: time1, to: time2)!)

Calculating the difference between two dates in Swift

I ended up creating a custom operator for Date:

extension Date {

static func - (lhs: Date, rhs: Date) -> TimeInterval {
return lhs.timeIntervalSinceReferenceDate - rhs.timeIntervalSinceReferenceDate
}

}

With this operator I can now compute the difference between two dates on a more abstract level without caring about timeIntervalSinceReferenceDate or what exactly the reference date is – and without losing precision, for example:

let delta = toDate - fromDate

Obviously, I didn't change much, but for me it's a lot more readable and consequent: Swift has the + operator already implemented for a Date and a TimeInterval:

/// Returns a `Date` with a specified amount of time added to it.
public static func + (lhs: Date, rhs: TimeInterval) -> Date

So it's already supporting

Date + TimeInterval = Date

Consequently, it should also support

Date - Date = TimeInterval

in my opinion and that's what I added with the simple implementation of the - operator. Now I can simply write the example function exactly as mentioned in my question:

func computeNewDate(from fromDate: Date, to toDate: Date) -> Date    
let delta = toDate - fromDate // `Date` - `Date` = `TimeInterval`
let today = Date()
if delta < 0 {
return today
} else {
return today + delta // `Date` + `TimeInterval` = `Date`
}
}

It might very well be that this has some downsides that I'm not aware of at this moment and I'd love to hear your thoughts on this.

How do I calculate time difference between current time and set time in Swift

The problem is that you are trying to convert an UILabel to a date, but you actually want to convert the text that's inside the UIlabel to a date.

Try changing:

let date1 = formatter.date(from: time1)!
let date2 = formatter.date(from: time2)!

To:

let date1 = formatter.date(from: time1.text!)
let date2 = formatter.date(from: time2.text!)


Related Topics



Leave a reply



Submit