获取当前时区自午夜以来的持续时间。

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

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.

huangapple
  • 本文由 发表于 2021年10月22日 07:13:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/69669746.html
匿名

发表评论

匿名网友

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

确定