英文:
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)
答案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?)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论