Golang : Calculate elapsed years or months since a date
This is additional tutorial to our previous tutorial on how to calculate elasped run time. We will learn how to calculate the elapsed time in years, month and day.
NOTE : it is important to note that if you're trying this out in play.golang.org, please note that the time started on :
2009-11-10 23:00:00
and
Here it is :
package main
import (
"fmt"
"time"
)
func main() {
format := "Jan 2, 2006" // just a format. not taken into calculation
date := "Oct 29, 1978"
start, _ := time.Parse(format, date)
end := time.Since(start)
years := end / time.Hour / 24 / 365
fmt.Printf("%d years passed since %s\n", years, date)
months := years * 12
fmt.Printf("%d months passed since %s\n", months, date)
// calculating days can be tricky - need to factor in leap years and timezones(daylight saving)
}
output :
36 years passed since Oct 29, 1978
432 months passed since Oct 29, 1978
and if the code is executed on http://play.golang.org/p/SDs6NkInrL
31 years passed since Oct 29, 1978
372 months passed since Oct 29, 1978
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+14.5k Golang : How to filter a map's elements for faster lookup
+12.9k Python : Convert IPv6 address to decimal and back to IPv6
+12.7k Golang : Remove or trim extra comma from CSV
+8.4k Golang: Prevent over writing file with md5 hash
+13.2k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+16.4k Golang : Find out mime type from bytes in buffer
+18.4k Golang : How to get hour, minute, second from time?
+5.7k Golang : Detect words using using consecutive letters in a given string
+6k Golang : Shuffle array of list
+14.6k Golang : How to check if your program is running in a terminal
+7.3k Golang : alternative to os.Exit() function
+14.6k Golang : GUI with Qt and OpenCV to capture image from camera