有没有时间库函数或其他好方法来获取Unix时间中最新的工作日、小时、分钟组合?例如,给定:
日期:周一
小时: 11
分钟: 30
现在是星期二,我想要昨天上午11:30的Unix时间一些语言/库支持thing,但我在Go中找不到可以让这件事变得简单的东西。有什么建议吗?
发布于 2021-04-27 09:22:22
如果你看看Weekday的定义,你会发现周日是0,周一是1,依此类推。所以要到达最后一个星期一,你必须回到今天-周一,并回到当天的11:30。然而,如果已经是周一并且在11:30之前,这就不起作用了,所以你需要检查一下:
now:=time.Now()
dayOffset:=now.Weekday()-time.Monday
targetDate:=now.AddDate(0,0,-int(dayOffset))
targetDate=time.Date(targetDate.Year(),targetDate.Month(),targetDate.Day(),11,30,0,0,targetDate.Location())
if targetDate.After(now) {
targetDate=targetDate.AddDate(0,0,-7)
}发布于 2021-04-27 09:41:27
我尝试了一种简单直观的解决方案。有关说明,请参阅代码注释
package main
import (
"fmt"
"time"
)
func main() {
// The target day / hour / minute
const (
day = time.Monday
hour = 21
minute = 0
)
// The starting time to work from
startTime := time.Now()
// Create the time on that day with the desired hour and minute
t := time.Date(startTime.Year(), startTime.Month(), startTime.Day(), hour, minute, 0, 0, startTime.Location())
// As long as we're on the wrong weekday, or not before the start time, back up one day
for t.Weekday() != day || !t.Before(startTime){
t = t.AddDate(0, 0, -1)
}
// Print the time, and it's Unix timestamp.
fmt.Println(t, t.Unix())
}https://stackoverflow.com/questions/67275624
复制相似问题