有没有一种简单的方法可以更改现有时间的小时数?

huangapple go评论139阅读模式
英文:

Is there an easy way to change the hour of an existing time?

问题

目前我能提供的最好的翻译如下,这段代码很长,容易出错:

cst, _ := time.LoadLocation("Asia/Shanghai")
orig := time.Now().In(cst)
new := time.Date(orig.Year(), orig.Month(), orig.Day(), 13, orig.Minute(), orig.Second(), orig.Nanosecond(), cst)
fmt.Printf("%v", new)

https://play.golang.org/p/dv_7rltueY6

英文:

So far the best that I have is this, which is long and it's easy to make a mistake:

cst, _ := time.LoadLocation("Asia/Shanghai")
orig := time.Now().In(cst)
new := time.Date(orig.Year(), orig.Month(), orig.Day(), 13, orig.Minute(), orig.Second(), orig.Nanosecond(), cst)
fmt.Printf("%v", new)

https://play.golang.org/p/dv_7rltueY6

答案1

得分: 1

在处理时间间隔时,使用算术运算可能会更容易。

// 不要这样做!
// const newHour = 13
// d := orig.Add(time.Duration(newHour - orig.Hour()) * time.Hour)

然而,在夏令时期间,这种方法将无法正常工作。你的原始代码几乎是正确的... time.Date() 函数会考虑到夏令时的情况,尽管在某些特殊情况下可能没有一个好的答案(比如在北美东部时间发生时钟前移时,将时间设置为凌晨1点30分会发生什么?)。

英文:

It may seem easier to do arithmetic with durations.

// NO!
// const newHour = 13
// d := orig.Add(time.Duration(newHour - orig.Hour()) * time.Hour)

However, this won't work during daylight savings. Your original code is about as correct as it can be... the time.Date() function will account for daylight savings, although there are certain edge cases with no good answer (what happens when you set the time to 1:30AM when the clocks go forward in North American eastern time?)

huangapple
  • 本文由 发表于 2021年8月26日 20:54:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/68938905.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定