Monday, July 15, 2024
HomeGolangTime distinction between two dates in Go (Golang)

Time distinction between two dates in Go (Golang)



To calculate the time distinction between two dates, e.g., years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds between one date and the opposite, use the Sub() technique on the time.Time struct. It calculates the distinction between the 2 dates. Then utilizing the built-in strategies, you possibly can decide the particular variety of hours, minutes, seconds, and so forth., which have handed in that distinction.

bundle primary

import (
    "fmt"
    "time"
)

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

    fmt.Printf("Years: %dn", int64(distinction.Hours()/24/365))
    fmt.Printf("Months: %dn", int64(distinction.Hours()/24/30))
    fmt.Printf("Weeks: %dn", int64(distinction.Hours()/24/7))
    fmt.Printf("Days: %dn", int64(distinction.Hours()/24))
    fmt.Printf("Hours: %.fn", distinction.Hours())
    fmt.Printf("Minutes: %.fn", distinction.Minutes())
    fmt.Printf("Seconds: %.fn", distinction.Seconds())
    fmt.Printf("Milliseconds: %dn", distinction.Milliseconds())
    fmt.Printf("Microseconds: %dn", distinction.Microseconds())
    fmt.Printf("Nanoseconds: %dn", distinction.Nanoseconds())
}

There aren’t any built-in strategies for calculating the variety of days, weeks, months, or years between two dates. You need to do it manually utilizing the Length.Hours() technique.

Output:

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments