Golang : Determine if time variables have same calendar day
Problem :
You have two or more variables that are of type time.Time
and you want to find out if they are the same.
Solution :
If the time.Time
variables are exactly the same up to minutes, you can use time.Equal()
function to determine of the time objects are the same or not. For example :
package main
import (
"fmt"
"time"
)
func main() {
date1 := time.Date(2015, time.November, 24, 23, 0, 0, 0, time.UTC)
date2 := time.Date(2015, time.November, 24, 23, 0, 0, 0, time.UTC)
fmt.Println("Date1 is the same as date2? : ", date2.Equal(date1))
}
Output :
Date1 is the same as date2 : true
However, the above method will become false if the hours, minutes or seconds are not equal. If you are looking to determine if the variables have the same calendar day, then you will need to break the time.Time
variable into day, month and year for comparison.
package main
import (
"fmt"
"time"
)
func main() {
date1 := time.Date(2015, time.November, 24, 23, 0, 0, 0, time.UTC)
date2 := time.Date(2015, time.November, 24, 11, 0, 0, 0, time.UTC)
// will become false, because of slight difference in hours !!
fmt.Println("Date1 is the same as date 2? : ", date2.Equal(date1))
//year1, month1, day1 := date1.Date()
//year2, month2, day2 := date2.Date()
if date1.Day() == date2.Day() {
fmt.Println("Day 1 is : ", date1)
fmt.Println("Day 2 is : ", date2)
fmt.Println("and they have the same calendar day eventhough they have different hours!")
}
}
Output :
Date1 is the same as date 2? : false
Day 1 is : 2015-11-24 23:00:00 +0000 UTC
Day 2 is : 2015-11-24 11:00:00 +0000 UTC
and they have the same calendar day even though they have different hours!
References :
https://www.socketloop.com/references/golang-time-time-equal-function-example
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
+8.1k Golang : Number guessing game with user input verification example
+33.3k Golang : All update packages with go get command
+17.5k Golang : How to make a file read only and set it to writable again?
+51.6k Golang : How to get time in milliseconds?
+5.2k Golang : Get S3 or CloudFront object or file information
+9.8k Golang : Find and replace data in all files recursively
+7.5k Golang : Generate human readable password
+5.2k Python : Delay with time.sleep() function example
+47.2k Golang : Convert int to byte array([]byte)
+12.4k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+7.1k Golang : Scanf function weird error in Windows
+5.9k Golang : Convert Chinese UTF8 characters to Pin Yin