kvothe838
kvothe838

Reputation: 97

Dealing with Timezones and Unix Timestamp in Golang

Given the following code:

https://go.dev/play/p/moLVHXIc4ba

It shows the next result:

now: 2009-11-10 23:00:00 +0000 UTC m=+0.000000001 | inLoc: 2009-11-10 18:00:00 -0500 -05unix | now: 1257894000 | inLoc: 1257894000

I don't get why when I call .Unix() to the date evaluated in Lima location, I get the same timestamp that original date in GMT.

I expect to get the timestamp corresponding to the original timestamp in GMT with 5 hours less as Lima has UTC -5.

Upvotes: 2

Views: 5548

Answers (1)

rocka2q
rocka2q

Reputation: 2804

I expect to get the timestamp corresponding to the original timestamp in GMT [UTC] with 5 hours less as Lima has UTC -5.

how can I get the timestamp with 5 hours less to pass to frontend?


You appear to be asking for this inLocTimestamp function. Five hours is 18,000 (5 * 60 * 60) seconds.

package main

import (
    "fmt"
    "time"
)

func inLocTimestamp(inLoc time.Time) int64 {
    _, offset := inLoc.Zone()
    ts := inLoc.Add(time.Duration(offset) * time.Second)
    return ts.Unix()
}

func inLocTimestampMilli(inLoc time.Time) int64 {
    _, offset := inLoc.Zone()
    ts := inLoc.Add(time.Duration(offset) * time.Second)
    return ts.UnixMilli()
}

func main() {
    loc, _ := time.LoadLocation("America/Lima")
    now := time.Now().Round(0)
    inLoc := now.In(loc)
    fmt.Printf("time       | now: %v | inLoc: %v\n", now, inLoc)
    fmt.Printf("unix       | now: %v | inLoc: %v\n", now.Unix(), inLoc.Unix())
    fmt.Printf("timestamp  | now: %v | inLoc: %v\n", now.Unix(), inLocTimestamp(inLoc))
    fmt.Printf("difference | inLoc: timestamp - unix = %v\n", inLocTimestamp(inLoc)-inLoc.Unix())
}

https://go.dev/play/p/IyzA4qZLLuS

time       | now: 2009-11-10 23:00:00 +0000 UTC | inLoc: 2009-11-10 18:00:00 -0500 -05
unix       | now: 1257894000 | inLoc: 1257894000
timestamp  | now: 1257894000 | inLoc: 1257876000
difference | inLoc: timestamp - unix = -18000

Upvotes: 4

Related Questions