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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭