Golang : Calculate time different
Problem :
You are looking to calculate the days between two dates. How to do that in Golang?
Solution :
Use the Time.Sub()
function to calculate the differences between the two dates in hour and then convert the hour differences to day.
For example :
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("Today : ", now.Format("Mon, Jan 2, 2006 at 3:04pm"))
longTimeAgo := time.Date(2010, time.May, 18, 23, 0, 0, 0, time.UTC)
// calculate the time different between today
// and long time ago
diff := now.Sub(longTimeAgo)
// convert diff to days
days := int(diff.Hours() / 24)
fmt.Printf("18th May 2010 was %d days ago \n", days)
}
Sample output :
Today : Mon, May 18, 2015 at 10:50am
18th May 2010 was 1825 days ago
Reference :
See also : Golang : Get current, epoch time and display by year, month and day
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
+7.6k Golang : Rename part of filename
+8.7k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+7.2k Golang : Transform lisp or spinal case to Pascal case example
+30.6k Get client IP Address in Go
+23.6k Golang : Read a file into an array or slice example
+7.8k Golang : Command line ticker to show work in progress
+24k Golang : Call function from another package
+20.3k Golang : Reset or rewind io.Reader or io.Writer
+33.1k Delete a directory in Go
+5.5k Golang : Display advertisement images or strings on random order
+9.5k Golang : Web(Javascript) to server-side websocket example
+15.2k Golang : How to add color to string?