Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

this is the way I am entering time

and I need difference of two times

this is the way I am entering time and I need difference of two times

like image 324
Dhaval Umraliya Avatar asked Feb 26 '18 09:02

Dhaval Umraliya


People also ask

How do I find the difference between two times in Swift?

To calculate the time difference between two Date objects in seconds in Swift, use the Date. timeIntervalSinceReferenceDate method.

How do you find the difference in timestamps?

Discussion: If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.

Can you subtract dates in Swift?

To subtract hours from a date in swift we need to create a date first. Once that date is created we have to subtract hours from that, though swift does not provide a way to subtract date or time, but it provides us a way to add date or date component in negative value.

How can I calculate the difference between two times that are in 24 hour format?

So if I select the time 21:00 - 00:00, this gives the output as -21. But actual value should be 3 hours. Furthermore if somebody select a time as 21:00 - 00:00 the difference should be 3 hours while if somebody select a time of 21:00 - 12:00 the difference should be 15 hours.


3 Answers

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)
like image 78
Arnab Avatar answered Sep 21 '22 14:09

Arnab


Here is the two steps you can follow to solve this -

No.1

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

No.2

TimeInterval measures seconds, not milliseconds:

let date1 = Date()
let date2 = Date(timeIntervalSinceNow: 12600) // 3:30
let diff = Int(date2.timeIntervalSince1970 - date1.timeIntervalSince1970)
let hours = diff / 3600
let minutes = (diff - hours * 3600) / 60
like image 22
Md Rashed Pervez Avatar answered Sep 20 '22 14:09

Md Rashed Pervez


If you have 2 Date objects, you can get the TimeInterval (aka Double) difference using:

let difference = date1.timeIntervalSince(date2)

If you want to display the difference between the dates you should use DateComponentsFormatter, either like this:

let differenceDescription = dateComponentsFormatter.string(from: difference)

Or you can skip getting the time interval directly and just call:

let differenceDescription = dateComponentsFormatter.string(from: date1, to: date2)

As with all formatters, don't create them every time you need to use them. They're very heavy objects to create and should be stored for re-use.

like image 20
Guy Kogus Avatar answered Sep 21 '22 14:09

Guy Kogus