Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

⏳ 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

🧊 Cube root in Go

shorts numbers math

🟦 Square root in Go

shorts numbers math

🍰 The maximum and minimum value of the int types in Go

shorts numbers math