Change timezone of time or date

Avatar of the author Willem Schots
23 Jan, 2024
~2 min.
RSS

User preferences, scheduling or legal requirements. There are situations where you will need to convert time.Time values to different timezones.

Often you will want to use “named” timezones: Europe/Amsterdam or America/New_York.

On most systems these timezones are stored in a “timezone database”. This database needs to be kept up to date because timezones and their rules change because of social or political reasons.

If you've ever seen a script or dockerfile that updates a tzdata package, now you know why.

The Go time package provides functionality to read timezones from a “IANA Time Zone database”.

There are two functions:

  • time.LoadLocation looks in a number of common locations for the database. Optionally you can import the time/tzdata package to embed the database files in your binary.
  • time.LoadLocationFromTZData allows you to specify a custom path to a database.

Loading and changing location

In this snippet we’ll load a new time.Location reference using the time.LoadLocation function.

By passing this reference to the t.In(loc *time.Location) method we can create a new time.Time value in that new location.

See the example below.

main.go
package main

import (
	"fmt"
	"log"
	"time"
)

func main() {
	// t1 is in the UTC timezone
	t1 := time.Date(2024, 01, 22, 13, 37, 0, 0, time.UTC)

	// load the Hong Kong location from the time zone database.
	hongKong, err := time.LoadLocation("Asia/Hong_Kong")
	if err != nil {
		log.Fatalf("failed to load location: %v", err)
	}

	// t2 represents the same time instant in the Hong Kong timezone (UTC+8)
	t2 := t1.In(hongKong)

	fmt.Println(t1.String())
	fmt.Println(t2.String())
	fmt.Printf("same time instant: %v\n", t1.Equal(t2))
}

In this example, we initially have a time value t1 in the UTC location.

We then load the location reference for "Asia/Hong_Kong or quit the program if that fails.

Finally, we call t1.In(hongKong) to create t2 in the Hong Kong location.

t1 and t2 represent the same time instant, but they will have different clock readings. t2 will read 8 hours before t1. Because the Hong Kong timezone is in UTC+8.

Run the example to verify this.

🎓

Subscribe to my Newsletter and Keep Learning.

Gain access to more content and get notified of the latest articles:

I send emails every 1-2 weeks and will keep your data safe. You can unsubscribe at any time.

Hello! I'm the Willem behind willem.dev

I created this website to help new Go developers, I hope it brings you some value! :)

You can follow me on Mastodon, Twitter/X or LinkedIn.

Thanks for reading!