Cookies management by TermsFeed Cookie Consent

⏳ Time difference between two dates in Go

shorts time

Please consider supporting us by disabling your ad blocker

To calculate the time difference between two dates, e.g., years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds between one date and the other, use the Sub() method on the time.Time struct. It calculates the difference between the two dates. Then using the built-in methods, you can determine the specific number of hours, minutes, seconds, etc., that have passed in that difference.

package main

import (
    "fmt"
    "time"
)

func main() {
    firstDate := time.Date(2022, 4, 13, 1, 0, 0, 0, time.UTC)
    secondDate := time.Date(2021, 2, 12, 5, 0, 0, 0, time.UTC)
    difference := firstDate.Sub(secondDate)

    fmt.Printf("Years: %d\n", int64(difference.Hours()/24/365))
    fmt.Printf("Months: %d\n", int64(difference.Hours()/24/30))
    fmt.Printf("Weeks: %d\n", int64(difference.Hours()/24/7))
    fmt.Printf("Days: %d\n", int64(difference.Hours()/24))
    fmt.Printf("Hours: %.f\n", difference.Hours())
    fmt.Printf("Minutes: %.f\n", difference.Minutes())
    fmt.Printf("Seconds: %.f\n", difference.Seconds())
    fmt.Printf("Milliseconds: %d\n", difference.Milliseconds())
    fmt.Printf("Microseconds: %d\n", difference.Microseconds())
    fmt.Printf("Nanoseconds: %d\n", difference.Nanoseconds())
}

There are no built-in methods for calculating the number of days, weeks, months, or years between two dates. You have to do it manually using the Duration.Hours() method.

Output:

Years: 1
Months: 14
Weeks: 60
Days: 424
Hours: 10196
Minutes: 611760
Seconds: 36705600
Milliseconds: 36705600000
Microseconds: 36705600000000
Nanoseconds: 36705600000000000

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

⏰ Handle HTTP timeout error in Go

shorts http

🐾 How to compare strings in Go

shorts introduction strings

🛑 Exit an app in Go

shorts introduction os