我试图找到一种方法来检查当前时间是否在给定的时间间隔内,其中开始和结束由用户给出(最终)。
我一直在尝试使用时间之前的After和Before ……
例如,
package main import ( "fmt" "strconv" "time" ) func inTimeSpan(start, end, check time.Time) bool { start, end = start.UTC(), end.UTC() if start.After(end) { start, end = end, start } check = check.UTC() return !check.Before(start) && !check.After(end) } func main() { now := time.Now() newLayout := "15:04" ns, _ := time.Parse(newLayout, strconv.Itoa(now.Hour())+":"+strconv.Itoa(now.Minute())) srt, _ := time.Parse(newLayout, "23:00") end, _ := time.Parse(newLayout, "05:00") fmt.Println(srt, end) fmt.Println(ns) fmt.Println("1 : ", inTimeSpan(srt, end, ns)) }
输出:
0000-01-01 23:00:00 +0000 UTC 0000-01-01 05:00:00 +0000 UTC 0000-01-01 20:37:00 +0000 UTC 1 : true