How to Parse Time in a Specific Timezone in Go?

Mary-Kate Olsen
Release: 2024-10-24 17:15:02
Original
617 people have browsed it

How to Parse Time in a Specific Timezone in Go?

Parsing Time in a Specific Timezone

When parsing a time string using time.ParseTime(), the resulting time struct is typically in UTC. However, if you require a different timezone, here's how you can achieve it:

Solution:

Utilize time.ParseInLocation to parse time in a given Location when the time zone is not explicitly specified. time.Local represents your local timezone, so passing it as the Location will resolve the issue:

<code class="go">import (
    "fmt"
    "time"
)

func main() {
    // Honor given time zone
    const formWithZone = "Jan 2, 2006 at 3:04pm (MST)"
    t, _ := time.ParseInLocation(formWithZone, "Jul 9, 2012 at 5:02am (CEST)", time.Local)
    fmt.Println(t)  // Output: 2012-07-09 05:02:00 +0000 CEST

    // Default to local time zone
    const formWithoutZone = "Jan 2, 2006 at 3:04pm"
    t, _ = time.ParseInLocation(formWithoutZone, "Jul 9, 2012 at 5:02am", time.Local)
    fmt.Println(t)  // Output: 2012-07-09 05:02:00 -0700 PDT
}</code>
Copy after login

In the first example, the time is parsed with a specified timezone (CEST) and returns a time struct in that timezone. In the second example, since no timezone is provided, the time is parsed in the local timezone (PDT).

The above is the detailed content of How to Parse Time in a Specific Timezone 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!