英文:
Obtain duration since last midnight in time zone
问题
我想获取一个时区自午夜以来的持续时间。
我尝试了以下代码:
estLocation, _ := time.LoadLocation("America/New_York")
nowEST := time.Now().In(estLocation)
midnightEST := nowEST.Truncate(24 * time.Hour)
diff := time.Since(midnightEST)
还尝试了使用Round
而不是Truncate
。
然而,这只是将时钟设置回了24小时,而不是返回东部标准时间(EST)的午夜时间。
如何实现这个目标?
英文:
I would like to obtain the duration since last midnight in a time zone.
I have tried the following:
estLocation, _ := time.LoadLocation("America/New_York")
nowEST := time.Now().In(estLocation)
midnightEST := nowEST.Truncate(24 * time.Hour)
diff := time.Since(midnightEST)
as well as using Round
instead of Truncate
.
However, this only sets back the clock by 24h instead of returning the midnight in EST.
How to achieve this?
答案1
得分: 5
通过从日期构造时间来获取午夜的时间:
loc, _ := time.LoadLocation("America/New_York")
now := time.Now().In(loc)
midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
从现在减去午夜以获取持续时间:
d := now.Sub(midnight)
在 playground 上运行它。请注意,time.Now() 在 playground 上是一个常量值。
英文:
Get the time for midnight by constructing a time from the date:
loc, _ := time.LoadLocation("America/New_York")
now := time.Now().In(loc)
midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
Subtract midnight from now to get the duration:
d := now.Sub(midnight)
Run it on the playground. Note that time.Now() is a constant value on the playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论