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
+32.2k Golang : Smarter Error Handling with strings.Contains()
+8.2k Golang : How to use Gorilla webtoolkit context package properly
+28.2k Golang : Save map/struct to JSON or XML file
+4.4k Javascript : Change page title to get viewer attention
+18.8k Swift : Convert (cast) Int to int32 or Uint32
+28.2k Golang : How to create new XML file ?
+10.6k Golang : Generate DSA private, public key and PEM files example
+4.6k Unix/Linux/MacOSx : How to remove an environment variable ?
+27k Golang : Change a file last modified date and time
+9.1k Golang : Detect number of faces or vehicles in a photo
+23.7k Golang : Change file read or write permission example
+17k Golang : Put UTF8 text on OpenCV video capture image frame