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
+4k Golang : ffmpeg with os/exec.Command() returns non-zero status
+3.3k Golang : Null and nil value
+7.4k Golang : How to force compile or remove object files first before rebuild?
+7.6k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+8.6k Golang : Read large file with bufio.Scanner cause token too long error
+6.9k Golang : Chunk split or divide a string into smaller chunk example
+5.2k Golang : Determine if time variables have same calendar day
+14.5k Golang : Delete item from slice based on index/key position
+21.4k Golang : Use wildcard patterns with filepath.Glob() example
+19.7k Golang : JQuery AJAX post data to server and send data back to client example
+4.3k Golang : Gomobile init produce "iphoneos" cannot be located error
+6.5k CodeIgniter : Load different view for mobile devices