【发布时间】:2015-11-06 21:25:16
【问题描述】:
我对 Go 很陌生,主要使用 C# 工作。我目前正在研究将用作获取下一班车的命令的东西。目前它无法编译,因为我正在努力理解如何在 Go 中使用 time 包。
我有一个字符串数组,它的格式设置为计划的时间,另一个格式为分钟,当它是常规服务时(还有更多时间,这些只是一个示例:
var ScheduledTimes = []string{"06:34", "06:54", "17:09", "17:19"}
var RegularTimes = []string{"05", "50"}
所以我目前正在做的是获取当前时间并通过这样做检查它是否在正常服务中:
func isWithinRegularService(check time.Time) bool {
RegularStart, err := time.Parse(time.Kitchen, "10:05")
RegularEnd, err := time.Parse(time.Kitchen, "13:52")
return check.After(RegularStart) && check.Before(RegularEnd)
}
time := time.Now().UTC().Format("15:04")
if isWithinRegularService(time) { }
如果它在正常服务中,我将确定需要查看的时间(即这一小时或下一小时内的下一个服务)
if time.Minutes < 5 && time.Minutes >= 0 {
RegularTimes[0] = fmt.Sprintf("%s%s", time.Hour+1, RegularTimes[0])
RegularTimes[1] = fmt.Sprintf("%s%s", time.Hour+1, RegularTimes[1])
RegularTimes[2] = fmt.Sprintf("%s%s", time.Hour+1, RegularTimes[2])
RegularTimes[3] = fmt.Sprintf("%s%s", time.Hour+1, RegularTimes[3])
} else {
RegularTimes[0] = fmt.Sprintf("%s%s", time.Hour, RegularTimes[0])
RegularTimes[1] = fmt.Sprintf("%s%s", time.Hour, RegularTimes[1])
RegularTimes[2] = fmt.Sprintf("%s%s", time.Hour, RegularTimes[2])
RegularTimes[3] = fmt.Sprintf("%s%s", time.Hour, RegularTimes[3])
}
在我将该数组传递给另一个函数之前,让我有时间检查
type BusTime struct {
betweenStart string
betweenEnd string
}
func getBusTime(busTimes []array, iteration int) BusTime {
var timesToReturn BusTime
if iteration == busTimes.Count()-1 {
timesToReturn.betweenStart = busTimes[iteration]
timesToReturn.betweenEnd = busTimes[0]
} else {
timesToReturn.betweenStart = busTimes[iteration]
timesToReturn.betweenEnd = busTimes[iteration+1]
}
return timesToReturn
}
busTimes := getBusTime(quaylinkRegularTimes, i)
最后,我检查提供的时间是否在要比较的时间之间:
check.After(start) && check.Before(end)
这就是这个项目的内容。如果它没有定期服务,它会做同样的事情,但会跳过确定要看的时间。
目前这还没有建立,因为我在应该使用时间的地方使用字符串,我希望获得一些指导、一些示例以及有关如何正确使用时间来实现我想要做的事情的更正。到目前为止,我相信我对这种流动方式的逻辑是正确的,但我坚持让它编译。
【问题讨论】:
-
您在尝试使用Times时遇到了什么问题?请展示您遇到的问题的最小示例。
-
嗨,我遇到的问题是我不明白如何从字符串转换为时间,我读过一些地方,当他们将字符串解析为时间时它们都包括日期,而我的只包括时间。
-
在没有日期的情况下单独使用小时和分钟是不明确的。 23:59 是在 00:01 之前还是之后?如果您只想使用小时和分钟,我会将它们作为整数使用。
-
我认为我的逻辑可以处理 23:59 和 00:01,但是无法检查它是否会处理。你将如何处理整数?
-
时间是特定位置的纳秒瞬间。您本质上要求的是从 00:00 开始的持续时间。您可以使用 Time.Duration,或者使用从 00:00 起仅使用分钟或秒的单个整数的方法直接使用所需格式的方法创建自己的类型。