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
+15.6k Golang : How to check if input from os.Args is integer?
+14k Golang : Find network of an IP address
+7.2k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+12.7k Golang : List objects in AWS S3 bucket
+8.9k Golang : Play .WAV file from command line
+16.2k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+17.9k Golang : How to get hour, minute, second from time?
+8.3k Golang : On lambda, anonymous, inline functions and function literals
+21.9k Golang : Read directory content with filepath.Walk()
+12.5k Python : Convert IPv6 address to decimal and back to IPv6
+6.9k Linux : How to fix Brother HL-1110 printing blank page problem
+7.5k Golang : How to feed or take banana with Gorilla Web Toolkit Session package