Time before 11 o'clock

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 {

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.

1 Like

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.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.