Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current timestamp in other timezones in Golang?

Tags:

go

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.

like image 838
Kartik Sura Avatar asked Jan 16 '15 19:01

Kartik Sura


People also ask

How do I get a TimeStamp from a zone?

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.

How do I change TimeZone in Golang?

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.

How can I get current date in Go lang?

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.


2 Answers

//init the loc loc, _ := time.LoadLocation("Asia/Shanghai")  //set timezone,   now := time.Now().In(loc) 
like image 84
陈敏华 Avatar answered Sep 20 '22 20:09

陈敏华


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).

like image 31
fabrizioM Avatar answered Sep 22 '22 20:09

fabrizioM