sm4ll_3gg
sm4ll_3gg

Reputation: 247

How to parse GMT timezone Golang

I have time zone id like this: (GMT+01:00) Brussels, Copenhagen, Madrid, Paris. What is the best way to get time.Location from this string?

Upvotes: 0

Views: 2915

Answers (1)

Marc
Marc

Reputation: 21155

You'll need to extract the zone name from your string, then turn it into a location.

You can do the first part using regexps, the latter with time.LoadLocation

package main

import (
    "fmt"
    "regexp"
    "time"
)

func main() {
    re := regexp.MustCompile(`^\(([A-Z]+)[+-:0-9]+\).*`)
    input := "(GMT+01:00) Brussels, Copenhagen, Madrid, Paris."

    matches := re.FindStringSubmatch(input)
    fmt.Println("Found timezone string: ", matches[1])

    l, _ := time.LoadLocation(matches[1])
    fmt.Println("Found timezone:", l)

    fmt.Println(time.Now())
    fmt.Println(time.Now().In(l))
}

This prints out:

$ go run ./main.go
Found timezone string:  GMT
Found timezone: GMT
2018-01-24 10:30:28.989832073 +0100 CET
2018-01-24 09:30:28.989860913 +0000 GMT

warning: I'm ignoring errors and non-matching regexp, you probably shouldn't.

Upvotes: 1

Related Questions