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
+10.8k Golang : Determine if time variables have same calendar day
+13.4k Golang : Parsing or breaking down URL
+29.4k Golang : Download file example
+10.1k How to test Facebook App on localhost ?
+7k Golang : Get all countries phone codes
+7.7k Golang : Executing and evaluating nested loop in html template
+18k Golang : Fix cannot download, $GOPATH not set error
+4.3k Golang : Get FX sentiment from website example
+37.7k Golang : How to read CSV file
+17.3k Golang : Send email with attachment
+5.3k Golang : Detect face in uploaded photo like GPlus
+19.8k Curl usage examples with Golang