Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a time offset to a location/timezone in Go

Tags:

timezone

go

Given an arbitrary time offset, how does one go about creating a usable time.Location object that represents that time offset?

The following code parses a time using an offset, but fmt.Println(t.Location()) subsequently returns no information:

func main() {
    offset := "+1100"

    t, err := time.Parse("15:04 GMT-0700","15:06 GMT"+offset)
    if err != nil {
        fmt.Println("fail", err)
    }
    fmt.Println(t)
    fmt.Println(t.UTC())
    fmt.Println(t.Location())
}

Playground: https://play.golang.org/p/j_E28qJ8Vgy

Basically I have some time data with time offsets, but without location data, I want to create a time.Location object to ensure the GMT offset is recorded. And then be able to output the time relative to the end users actual location time offset.

like image 234
Jay Avatar asked Mar 29 '19 06:03

Jay


People also ask

How do you offset time zones?

The zone offset can be Z for UTC or it can be a value "+" or "-" from UTC. For example, the value 08:00-08:00 represents 8:00 AM in a time zone 8 hours behind UTC, which is the equivalent of 16:00Z (8:00 plus eight hours). The value 08:00+08:00 represents the opposite increment, or midnight (08:00 minus eight hours).

Does timezone offset change?

An offset is the number of hours or minutes a certain time zone is ahead of or behind GMT**. A time zone's offset can change throughout the year because of Daylight Saving Time.

What is UTC time zone offset?

What is a UTC offset? A UTC offset is the difference in hours and minutes between a particular time zone and UTC, the time at zero degrees longitude. For example, New York is UTC-05:00, which means it is five hours behind London, which is UTC±00:00.


1 Answers

Use:

loc := time.FixedZone("UTC+11", +11*60*60)

Then set to this location:

t = t.In(loc)

Try this:

package main

import (
    "fmt"
    "time"
)

func main() {
    loc := time.FixedZone("UTC+11", +11*60*60)

    t := time.Now()
    fmt.Println(t)
    fmt.Println(t.Location())

    t = t.In(loc)
    fmt.Println(t)
    fmt.Println(t.Location())

    fmt.Println(t.UTC())
    fmt.Println(t.Location())
}

Output:

2009-11-10 23:00:00 +0000 UTC m=+0.000000001
UTC
2009-11-11 10:00:00 +1100 UTC+11
UTC+11
2009-11-10 23:00:00 +0000 UTC
UTC+11
like image 69
wasmup Avatar answered Sep 29 '22 23:09

wasmup