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
+4.7k Golang : How to pass data between controllers with JSON Web Token
+13.2k Golang : How to calculate the distance between two coordinates using Haversine formula
+9.4k Golang : Play .WAV file from command line
+19.5k Golang : How to Set or Add Header http.ResponseWriter?
+6.9k Golang : Muxing with Martini example
+5.4k Golang : Reclaim memory occupied by make() example
+10.1k Golang : Print how to use flag for your application example
+12.6k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+9k Golang : Capture text return from exec function example
+7.7k Golang : Mapping Iban to Dunging alphabets
+3.6k Java : Get FX sentiment from website example
+9.2k Golang : Write multiple lines or divide string into multiple lines