Home > Backend Development > Golang > Why Does Manually Adding UTC Offset Fail to Accurately Convert UTC to Local Time in Go?

Why Does Manually Adding UTC Offset Fail to Accurately Convert UTC to Local Time in Go?

Linda Hamilton
Release: 2024-12-26 06:25:11
Original
151 people have browsed it

Why Does Manually Adding UTC Offset Fail to Accurately Convert UTC to Local Time in Go?

Convert UTC to Local Time in Go with Precision

Question:

In an attempt to convert UTC time to local time for specific countries, a Go program encounters incorrect results despite considering the UTC difference. What could be the underlying issue?

Answer:

The error arises when the time is being calculated by manually adding the UTC difference as a duration. This approach does not account for other factors, such as daylight saving time (DST).

To accurately convert UTC time to local time, the correct method is to use time.LoadLocation. Here's how you can do it:

import "time"

// A map of country names to their time zone names
var countryTz = map[string]string{
    "Hungary": "Europe/Budapest",
    "Egypt":   "Africa/Cairo",
}

// Function to convert UTC time to the local time of a specific country
func timeIn(name string) time.Time {
    loc, err := time.LoadLocation(countryTz[name])
    if err != nil {
        panic(err)
    }
    return time.Now().In(loc)
}

// Example usage
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

This code first defines a mapping of country names to their corresponding time zone names. Then, time.LoadLocation is used to obtain the specific time zone for a given country. By calling time.Now().In(loc), the current UTC time is converted to the local time for the desired country, taking into account DST and other factors.

The above is the detailed content of Why Does Manually Adding UTC Offset Fail 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