Home > database >  Obtain duration since last midnight in time zone
Obtain duration since last midnight in time zone

Time:10-23

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?

CodePudding user response:

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.

  • Related