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
+17.6k Golang : Parse date string and convert to dd-mm-yyyy format
+4.7k Linux/MacOSX : How to symlink a file?
+10k Golang : Setting variable value with ldflags
+12.6k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+34.6k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+14.3k Golang : Parsing or breaking down URL
+10.1k Golang : How to tokenize source code with text/scanner package?
+8.9k Golang : Get SPF and DMARC from email headers to fight spam
+8.2k Golang : Check if integer is power of four example
+8.2k Golang : Metaprogramming example of wrapping a function
+25.3k Golang : Convert long hexadecimal with strconv.ParseUint example
+5.4k Golang : fmt.Println prints out empty data from struct