How to get the current timestamp in other timezones in Golang?
GoTimestampTimezoneGo Problem Overview
I need to get the current time in different time-zones.
Currently I know that we can do the following:
t := time.Now()
fmt.Println("Location:", t.Location(), ":Time:", t)
utc, err := time.LoadLocation("America/New_York")
if err != nil {
fmt.Println("err: ", err.Error())
}
fmt.Println("Location:", utc, ":Time:", t.In(utc))
The LoadLocation name is taken to be a location name corresponding to a file in the IANA Time Zone database, such as "America/New_York".
Is there a simpler way to get the current time, if the country name, or the GMT offset is given e.g +530 for India?
Edit: I would also want to support Day light savings.
Go Solutions
Solution 1 - Go
//init the loc
loc, _ := time.LoadLocation("Asia/Shanghai")
//set timezone,
now := time.Now().In(loc)
Solution 2 - Go
No, that is the best way. You can create your custom Location
using FixedZone and use that custom location.
> FixedZone returns a Location that always uses the given zone name and > offset (seconds east of UTC).
Solution 3 - Go
I like this way
//init the loc
loc, _ := time.LoadLocation("Asia/Shanghai")
//set timezone,
now := time.Now().In(loc)
Where can I find the name of the location?
> You can see it on the zoneinfo.zip
some example
package _test
import (
"fmt"
"testing"
"time"
)
func TestTime(t *testing.T) {
myT := time.Date(2022, 4, 28, 14, 0, 0, 0, time.UTC)
for _, d := range []struct {
name string
expected string
}{
{"UTC", "2022-04-28 14:00:00 +0000 UTC"},
{"America/Los_Angeles", "2022-04-28 07:00:00 -0700 PDT"},
{"Asia/Tokyo", "2022-04-28 23:00:00 +0900 JST"},
{"Asia/Taipei", "2022-04-28 22:00:00 +0800 CST"},
{"Asia/Hong_Kong", "2022-04-28 22:00:00 +0800 HKT"},
{"Asia/Shanghai", "2022-04-28 22:00:00 +0800 CST"},
} {
loc, _ := time.LoadLocation(d.name)
if val := fmt.Sprintf("%s", myT.In(loc)); val != d.expected {
fmt.Println(val)
t.FailNow()
}
}
}