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.
You cannot “ get a TimeZone ID from a certain TimeStamp”, that is impossible. Your count-from-epoch was made while accounting for a certain time zone, usually UTC. If must know that intended zone used in creating that count-from-epoch, it cannot be deduced.
You can achieve what you want from inside your app using os. Setenv("TZ", "Africa/Cairo") , what matters is that you must call this before any other package uses anything from the time package.
Using the “time. Now()” function you can get the date and time in the “yyyy-mm-dd hh:mm:ss. milliseconds timezone” format. This is simplest way for getting the date and time in golang.
//init the loc loc, _ := time.LoadLocation("Asia/Shanghai") //set timezone, now := time.Now().In(loc)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With