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
+18.3k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+12.6k Javascript : Prompt confirmation before exit
+9.4k Golang : Underscore string example
+16.3k Golang : [json: cannot unmarshal object into Go value of type]
+33.5k Golang : Upload and download file to/from AWS S3
+20.6k Golang : How to reverse slice or array elements order
+7.7k Golang : Accept any number of function arguments with three dots(...)
+6k Golang : Mapping Iban to Dunging alphabets
+8.9k Golang : Setting variable value with ldflags
+6.8k Golang : get the current working directory of a running program
+7.9k Golang : How to get username from email address
+3.8k Facebook : How to place save to Facebook button on your website