Golang : Comparing date or timestamp
Problem :
You have to compare two timestamps to see if the they are equal or not.
Solution :
Use time.Equal()
function to compare the timestamps. 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)
// compare time with time.Equal()
sameTime := longTimeAgo.Equal(now)
fmt.Println("longTimeAgo equals to now ? : ", sameTime)
// 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 :
./timecompare
Today : Wed, May 27, 2015 at 12:38am
longTimeAgo equals to now ? : false
18th May 2010 was 1834 days ago
References :
http://godoc.org/time#Time.Equal
https://www.socketloop.com/tutorials/golang-calculate-time-different
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
+5.1k JavaScript/JQuery : Redirect page examples
+9.4k Golang : Read file with ioutil
+15.3k Golang : invalid character ',' looking for beginning of value
+14.3k Golang : How to determine if user agent is a mobile device example
+10.7k Golang : Command line file upload program to server example
+22.4k Generate checksum for a file in Go
+15.1k Golang : How to get Unix file descriptor for console and file
+13.3k Golang : Count number of runes in string
+8.9k Golang : Capture text return from exec function example
+17.6k Golang : How to make a file read only and set it to writable again?
+20.5k Golang : Secure(TLS) connection between server and client
+14.2k Golang : How to convert a number to words