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
+12.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+26.5k Get file path of temporary file in Go
+11.7k Generate salted password with OpenSSL example
+5.9k Golang : constant 20013 overflows byte error message
+27.9k Golang : missing Git command
+27.8k Golang : Save map/struct to JSON or XML file
+14.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+19.8k Golang : Get password from console input without echo or masked
+4.5k Javascript : Shuffle or randomize array example
+16.9k Golang : Find IP address from string
+10.5k Golang : Sort and reverse sort a slice of runes
+7.9k Golang : Generate EAN barcode