duanfei1930 2019-03-28 15:21
浏览 8
已采纳

如何检查期间中日期的出现

In my Go application, I am trying to check the occurrence of a date in a period.

if survey.StartPeriod.Before(time.Now()) && survey.EndPeriod.After(time.Now()) {
    fmt.Println("1 BLOCK")
}
else if survey.EndPeriod.Before(time.Now()) {
    fmt.Println("2 BLOCK")
}

If I have such incoming data (current time inside period):

Current TIME | 2019-03-28 21:02:47.0377305 +0600 +06 m=+60.748044601
START_PERIOD | 2019-03-28 21:00:00 +0000 +0000
END_PERIOD   | 2019-03-28 21:05:00 +0000 +0000

I want to run code inside 1 block. My current code run that block only if I use Before function to both periods. I am not sure that it's correct.

If I have such incoming data (current time outside the end_period):

Current TIME | 2019-03-28 21:10:47.0377305 +0600 +06 m=+60.748044601
START_PERIOD | 2019-03-28 21:00:00 +0000 +0000
END_PERIOD   | 2019-03-28 21:05:00 +0000 +0000

I want to run code inside 2 block. Right know it works incorrect. How to correctly make this program logic?

EDIT:

As you can see CURRENT_TIME inside range.

CURRENT_TIME | 2019-03-29 08:32:06.1375323 +0600 +06 m=+60.318452301
START_PERIOD | 2019-03-29 08:30:00 +0000 +0000
END_PERIOD   | 2019-03-29 08:31:00 +0000 +0000

When I try to test function InTimeSpan it return false value which is not correct. I am really confused. Why it happens?!

log.Println(InTimeSpan(survey.StartPeriod, survey.EndPeriod, time.Now()))
// return false
  • 写回答

1条回答 默认 最新

  • doucigua0278 2019-03-28 20:12
    关注

    What you are currently checking is if your current time is in the given range. You might want to swap time.Now with another time to check the occurrence of the date.

    However a couple things to consider:

    • make this logic to an outside function, as it needs to respond with true or false only, something like this it is as easy as:
    func InTimeSpan(start, finish time.Time, timeToCheck time.Time) bool {
        return start.Before(timeToCheck) && finish.After(timeToCheck)
    } 
    
    • make all times to the same timezone. Might be helpful if the timezone of the time you are checking is different, and this avoids some of the edge cases, something like this:
    func InTimeSpan(start, finish time.Time, timeToCheck time.Time) bool {
        return start.UTC().Before(timeToCheck) && finish.UTC().After(timeToCheck)
    }
    

    Really lame demo: https://play.golang.org/p/rzv3coztN4Z

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大