Time before 11 o'clock


(Markus Bolder) #1

I am looking for the easiest way to check if time.Now() is between 4 o’clock and 11 o’clock in the morning. I found lots of examples with fixed dates, but nothing that will just check the time without the date part. So far I am using the following code, but that won’t work if i want to check 11:15 :

t := time.Now()
	if t.Hour() < 11 {

(Curtis Allyn Green) #2

Could you do something like this? https://play.golang.org/p/T1cQJSQjAmr

Edited the example, seems you’ll need a little extra checking to elicit appropriate behavior.


(Johan Dahl) #3

Do you meen 11.15 is ok? You could check like this

t.Hour() >= 4 && t.Hour() < 12

Or if you want to check from 4:00:00 to 11:00:00 could you do it with this function

func betweenHours(t time.Time, fromHour, toHour int) bool {
	hour, min, sec := t.Clock()
	return hour >= fromHour && (hour < toHour ||
		hour == toHour && min == 0 && sec == 0)
}

this will only fail for the time between 11:00:00.000…00001 and 11:00:00.999…9999 but maybe it doesn’t matter.