Home > Backend Development > Golang > How to Calculate the Difference Between Two Time Instances in Go?

How to Calculate the Difference Between Two Time Instances in Go?

Linda Hamilton
Release: 2024-12-09 04:56:09
Original
223 people have browsed it

How to Calculate the Difference Between Two Time Instances in Go?

Determining Time Differences

You have two time.Time instances, and you need to calculate their difference in hours, minutes, and seconds. Consider the scenarios:

  • t1 = "2016-09-09 19:09:16 0530 IST"
    t2 = "2016-09-09 19:09:16 0530 IST"
    (Result: 00:00:00)
  • t1 = "2016-09-14 14:12:48 0530 IST"
    t2 = "2016-09-14 14:18:29 0530 IST"
    (Result: 00:05:41)

Solution

To calculate the difference, use the Time.Sub() function. The result is a time.Duration value.

Time.Duration prints itself intelligently:

package main

import (
    "fmt"
    "time"
)

func main() {
    t1 := time.Now()
    t2 := t1.Add(time.Second * 341)

    fmt.Println(t1)
    fmt.Println(t2)

    diff := t2.Sub(t1)
    fmt.Println(diff)
}
Copy after login

Output:

2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:05:41 +0000 UTC
5m41s
Copy after login

For a time format of HH:mm:ss, construct a time.Time value and use its Time.Format() method:

out := time.Time{}.Add(diff)
fmt.Println(out.Format("15:04:05"))
Copy after login

Output:

00:05:41
Copy after login

This works for time differences under 24 hours. For larger differences, consider using a solution that includes days, months, and years.

The above is the detailed content of How to Calculate the Difference Between Two Time Instances in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template