Golang time.Time.Sub() function example
package time
Golang time.Time.Sub() function usage example. Useful in calculating time differences or elapsed time.
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, Aug 10, 2015 at 12:05pm
18th May 2010 was 1909 days ago
References :
https://www.socketloop.com/tutorials/golang-calculate-time-different
Advertisement
Something interesting
Tutorials
+6.6k Golang : Warp text string by number of characters or runes example
+4.7k PHP : Extract part of a string starting from the middle
+5.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+31.7k Golang : How to convert(cast) string to IP address?
+5.2k Golang : Issue HTTP commands to server and port example
+10.4k Golang : Meaning of omitempty in struct's field tag
+9k Golang : automatically figure out array length(size) with three dots
+9.2k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+25.3k Golang : Convert uint value to string type
+11.4k Golang : Concatenate (combine) buffer data example
+8.8k Golang : HTTP Routing with Goji example