douzhongjian0752
2019-03-11 00:06
浏览 261
已采纳

检查当前时间是否在给定间隔GOLANG中

I am trying to find a way to check if the current time is in a given interval, where start and end are given (eventually) by a user.

I have been trying by using the After and Before from the Time package after making sure all times are in UTC, but clearly I am doing something wrong.

The code looks similar to this example:

func inTimeSpan(start, end, check time.Time) bool {
    return check.After(start) && check.Before(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("1 : ", inTimeSpan(srt, end, ns))
}

Any help is appreciated.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • douxigai8757 2019-03-11 00:27
    最佳回答
    func inTimeSpan(start, end, check time.Time) bool {
        if check.After(end) {
            return false
        }
        if end.After(start) {
            return check.After(start)
        }
        return check.Before(start)
    }
    

    Check it on playground https://play.golang.org/p/ISFpxzIjvY_L

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func inTimeSpan(start, end, check time.Time) bool {
        if check.After(end) {
            return false
        }
        if end.After(start) {
            return check.After(start)
        }
        return check.Before(start)
    }
    
    func main() {
        test := []struct {
            start string
            end   string
            check string
        }{
            {"23:00", "05:00", "04:00"},
            {"23:00", "05:00", "23:30"},
            {"23:00", "05:00", "20:00"},
            {"10:00", "21:00", "11:00"},
            {"10:00", "21:00", "22:00"},
            {"10:00", "21:00", "03:00"},
        }
        newLayout := "15:04"
        for _, t := range test {
            check, _ := time.Parse(newLayout, t.check)
            start, _ := time.Parse(newLayout, t.start)
            end, _ := time.Parse(newLayout, t.end)
            fmt.Println(t.start+"-"+t.end, t.check, inTimeSpan(start, end, check))
        }
    }
    

    Result:

    23:00-05:00 04:00 true
    23:00-05:00 23:30 false
    23:00-05:00 20:00 false
    10:00-21:00 11:00 true
    10:00-21:00 22:00 false
    10:00-21:00 03:00 false
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题