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

检查当前时间是否在给定间隔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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器