如何创建一个函数来判断当前时间是否在指定时间范围内
Golang不知道大家是否熟悉?今天我将给大家介绍《如何创建一个函数来判断当前时间是否在指定时间范围内》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!
我正在尝试找到一种方法来检查当前时间是否在时间窗口内。
输入是:
upgradeday []string - 一段日期(例如 ["sunday", "tuesday"])
upgradetime string - 小时:分钟(例如 "22:04")
upgradeduration int64 - 时间量,来自时间窗口有效的 upgradetime。最长可达 12 小时。
完整示例:
upgradeday = ["sunday", tuesday"] , upgradetime = "10:00", upgradeduration = 2 -> 时间窗口为每周日和周二,从 10:00 到 12:00 点。
我尝试编写以下函数,但它在天/月/年之间的转换中不起作用:
func isInsideTimeWindow(upgradeDay []string, upgradeTime string, upgradeDuration int64) bool {
now := time.Now()
ut := strings.Split(upgradeTime, ":")
hour, _ := strconv.Atoi(ut[0])
min, _ := strconv.Atoi(ut[1])
// !! not working when now it's Monday 00:01 and got: upgradeDay = ["Sunday"], upgradeTime = 23:59, upgradeDuration = 2
twStart := time.Date(now.Year(), now.Month(), now.Day(), hour, min, 0, 0, now.Location())
twEnd := twStart.Add(time.Hour * time.Duration(upgradeDuration))
if !(now.After(twStart) && now.Before(twEnd)) {
return false
}
wd := now.Weekday().String()
for i := range upgradeDay {
if upgradeDay[i] == wd {
return true
}
}
return false
}
有人知道如何在 go 中解决这个问题吗?
解决方案
时代有很多复杂性。例如:
- 如果升级日是“søndag”(丹麦语)而不是“星期日”怎么办?
- 我们应该使用当地时间还是 utc 时间?如果是本地的,谁的位置重要?如果服务器在伦敦而我在旧金山,我们使用服务器的时间还是我的时间?
- 如果升级间隔包括凌晨 2 点,那么是否也计算太平洋夏令时上午 2 点和太平洋标准时间上午 2 点?我住的地方这些时间相差一小时。如果该时间间隔从凌晨 2 点开始,到 2:59:59 结束,则在许多夏令时转变为一小时的地区,一年中的某一天不存在该时间。
如果您忽略所有这些复杂性 - 国际化 (i18n)、本地化 (l10n)、dst 等等 - 某人可以设置日期和时间或升级这一事实仍然存在一些问题其本身可能需要一些时间,但通常我们也会忽略这些。
请注意,go 的 time.now() 返回本地时间,但是,谁的位置?由于我们尚未回答使用谁的时区问题,因此我们可能希望避免担心这一点。考虑到其余的输入约束,让我们编写一个函数来确定提供的时间是否满足输入约束,而不是 time.now() 是否满足输入约束。然后,调用者可以提供 utc 时间或用户所在位置的挂钟时间:
somenow = time.time() localnow = somenow.in(location) // from time.loadlocation() or similar
我们还有一些与您的类型似乎不一致的东西:
upgradeduration int64 - 从升级时间算起的时间量,在该时间窗口有效。最长可达 12 小时
0 到 12 之间的小时值很容易适合普通 int。这是否已经是一个以纳秒表示的 time.duration 值?如果是这样,为什么是 int64 而不是 time.duration?或者它是以秒为单位的值,因此可以在 0 到 43200 之间?如果是这样,它仍然适合 int。
我做了很多假设并得出以下结论,您可以在 Go Playground 上尝试一下。
package main
import (
"fmt"
"strconv"
"strings"
"time"
)
// startok determines whether the given starting-time is within a
// time window.
//
// the window starts at a time given as two integers,
// h and m, representing hours and minutes, and extends for
// the given duration d in hours, which in general should not
// extend into another day. if it does extend past the end of
// the day into the next day, we ignore the extension.
//
// the days on which the time *is* in that window are further
// limited by the days[] slice of weekday values.
//
// note: it would probably be sensible to return a time.duration
// value that is how long it will be until the next ok time, but
// we leave that as an exercise.
//
// it would also be sensible to allow the duration d to extend
// into the next day, which is also left as an exercise.
func startok(when time.time, days []time.weekday, h, m, d int) bool {
// find ok-to-start time, and end-time. if end exceeds
// 24*60, we ignore the extra end time, rather than
// allowing some minutes into the next day.
start := h*60 + m
end := start + d*60
// convert when to hour-and-minute and see if we are
// in the allowed range.
wh, wm, _ := when.clock()
now := wh*60 + wm
if now < start || now >= end {
// not in hh:mm through hh+d:mm; say no.
return false
}
// the time-of-day is ok; check the day-of-week.
// we could do this earlier but by positioning it
// here, we leave room to check to see if it's
// the *next* day, if needed.
if !func(wd time.weekday) bool {
for _, allowed := range days {
if wd == allowed {
return true
}
}
return false
}(when.weekday()) {
return false // when.weekday() not in days[]
}
// time is ok, day is ok
return true
}
// startokstr is like startok but the window starts at a time
// given as a string encoded as hh:mm, with the days being a
// slice of strings instead of weekday. because of these strings,
// parsing can produce an error, so this function has an error
// return.
func startokstr(when time.time, days []string, hhmm string, d int) (bool, error) {
parts := strings.split(hhmm, ":")
// optional: be strict about two-digit values
if len(parts) != 2 {
return false, fmt.errorf("invalid time string %q", hhmm)
}
h, err := strconv.atoi(parts[0])
if err != nil {
return false, err
}
if h < 0 || h >= 60 {
return false, fmt.errorf("invalid hour value %s", parts[0])
}
m, err := strconv.atoi(parts[1])
if err != nil {
return false, err
}
if m < 0 || m >= 60 {
return false, fmt.errorf("invalid minute value %s", parts[1])
}
var wd []time.weekday
for _, s := range days {
w, err := parseweekday(s)
if err != nil {
return false, err
}
wd = append(wd, w)
}
ok := startok(when, wd, h, m, d)
return ok, nil
}
// parseweekday handles weekday strings.
//
// ideally we'd use time.parse for this, as it already has
// these in it, but they are not exported in usable form.
func parseweekday(s string) (time.weekday, error) {
strtoweekday := map[string]time.weekday{
"sunday": time.sunday,
"monday": time.monday,
"tuesday": time.tuesday,
"wednesday": time.wednesday,
"thursday": time.thursday,
"friday": time.friday,
"saturday": time.saturday,
}
if v, ok := strtoweekday[s]; ok {
return v, nil
}
return time.sunday, fmt.errorf("invalid day-of-week %q", s)
}
// tests should be converted to real tests and put in
// a separate file.
func tests() {
okdays := []string{"sunday", "wednesday"}
okstart := "04:00"
okduration := 2 // hours
tfmt := "mon jan 2 15:04:05 2006"
t1 := "sat sep 5 04:30:00 2020" // time ok, day not
t2 := "sun sep 6 04:30:00 2020" // time ok, day ok
check := func(s string, expect bool) {
when, err := time.parse(tfmt, s)
if err != nil {
panic(err)
}
result, err := startokstr(when, okdays, okstart, okduration)
if err != nil {
panic(err)
}
if result != expect {
fmt.printf("fail: expected %v for %q\n", expect, s)
}
}
check(t1, false)
check(t2, true)
fmt.println("2 tests run")
}
func main() {
tests()
}这是解决该问题的一种方法:
package main
import "time"
type window struct { time.Time }
func (w window) isDay(s string) bool {
return w.Weekday().String() == s
}
func (w window) isHourRange(begin, end int) bool {
return w.Hour() >= begin && w.Hour() <= end
}
func main() {
w := window{
time.Now(),
}
{
b := w.isDay("Friday")
println(b)
}
{
b := w.isHourRange(20, 23)
println(b)
}
}
这假设只有一天有效,因此您需要修改它来处理 多日。不过,这应该可以帮助您入门。
终于介绍完啦!小伙伴们,这篇关于《如何创建一个函数来判断当前时间是否在指定时间范围内》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
深入了解conda虚拟环境的优点和操作要点
- 上一篇
- 深入了解conda虚拟环境的优点和操作要点
- 下一篇
- 逐步学习Java变量设置的指南
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 478浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3191次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3403次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3434次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4541次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3812次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览

