Home > Backend Development > Golang > How to Accurately Convert UTC to Local Time in Go?

How to Accurately Convert UTC to Local Time in Go?

Patricia Arquette
Release: 2025-01-04 09:31:35
Original
137 people have browsed it

How to Accurately Convert UTC to Local Time in Go?

How to Convert UTC to Local Time in Go

Problem Statement

Converting UTC time to local time can be a challenge, especially when considering time zone variations. In Go, some users have encountered incorrect results when attempting to add UTC time offset durations to the current time.

Solution

The issue lies in the handling of time zones. While adding the time offset duration can adjust the time value, it does not account for the specific time zone's rules and DST (Daylight Saving Time) changes. To accurately convert UTC to local time, the proper way is to use the time.LoadLocation function.

Code Example

The following code demonstrates how to use time.LoadLocation to obtain local time in specific locations:

var countryTz = map[string]string{
    "Hungary": "Europe/Budapest",
    "Egypt":   "Africa/Cairo",
}

func timeIn(name string) time.Time {
    loc, err := time.LoadLocation(countryTz[name])
    if err != nil {
        panic(err)
    }
    return time.Now().In(loc)
}

func main() {
    utc := time.Now().UTC().Format("15:04")
    hun := timeIn("Hungary").Format("15:04")
    eg := timeIn("Egypt").Format("15:04")
    fmt.Println(utc, hun, eg)
}
Copy after login

In this example, countryTz defines a map of countries and their corresponding time zone names. The timeIn function loads the appropriate time zone and converts the current time to the local time in that time zone.

By using time.LoadLocation, the code ensures that time zone rules and DST adjustments are taken into account, providing accurate local times.

The above is the detailed content of How to Accurately Convert UTC to Local Time in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template