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
+10.4k Golang : Find and draw contours with OpenCV example
+29.5k error: trying to remove "yum", which is protected
+4.9k Golang : Compound interest over time example
+7.2k Golang : Ackermann function example
+10k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+5.4k Golang : Find the longest line of text example
+12.5k Golang : How to determine if a year is leap year?
+7.2k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+3.8k Golang : Calculate a pip value and distance to target profit example
+12.7k Elastic Search : Mapping date format and sort by date
+5.1k Golang : Experimental emojis or emoticons icons programming language
+5.2k PHP : Proper way to get UTF-8 character or string length