GoLang Time in UTC, PST, and EST

Timezones differ by country. Times differ by time zones. So, it’s really important to keep track of all the time zones there are and the conversions between them. In this post, we are going to take a look at different time zone conversions in GoLang.

Get time in different timezones

Now, we will see how we can get time in different time zones. For this, we will import the time package.

import "time"

Then we will use the LoadLocation() method. It will take a string containing either a timezone or a location of a specific time.

Then we can use the In function to generate time for that location.

package main

import (
	"fmt"
	"time"
)

func main() {
	// load time zone
	loc, e := time.LoadLocation("EST")       // use other time zones such as MST, IST
	CheckError(e)

	// get time in that zone
	fmt.Println(time.Now().In(loc)) // 2020-03-26 14:31:00.6625139 -0500 EST
}

func CheckError(e error) {
	if e != nil {
		fmt.Println(e)
	}
}

Here in this code, the time zone is first loaded and then the time now function is invoked using that zone.

Convert UTC time to other timezones

UTC stands for Coordinated Universal Time. Now, we will convert the current UTC time to PST, EST. It is just like the previous method of generating time in that location. The only difference now being using the UTC function to create a time object and then using that function.

package main

import (
	"fmt"
	"time"
)

func main() {
	// load time zone
	loc, e := time.LoadLocation("America/Los_Angeles")
	CheckError(e)

	// get time in that zone
	fmt.Println(time.Now().UTC().In(loc)) // 2020-03-26 12:41:35.8479431 -0700 PDT
}

func CheckError(e error) {
	if e != nil {
		fmt.Println(e)
	}
}