Golang, get the difference between two times in years
June 06, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To get the difference between two times in years,
- subtract times using the time
Sub()
method. - Use the
Hours()
method to get difference time in hours and divide it by/24/365
.
Today, I’m going to show you how do you get the difference between two times in years in golang, here we will use the golang time.Sub()
method to subtract time, and time.Hours()
to get the difference in years.
Let’s start today’s tutorial How do I get difference between two times in years in golang?
Here, we are going to do,
- Define two date times object.
- Use
Sub()
to get difference time. - Use the
Hours()
method and divide it by/24/365
to get the difference in years.
package main
import (
"fmt"
"time"
)
func main() {
currentTime := time.Now()
oldTime := time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC)
diff := currentTime.Sub(oldTime)
//In years
fmt.Printf("years: %f\n", diff.Hours() /24/365)
}
The above program will print a number of years between two dates in the golang console, let’s check the output.
All the best 👍