Help with reading Time from json

I’m trying to deparse Time from json. Can someone explain me, why these Times are not equal?

https://play.golang.org/p/uypxBiOhQGw

Time zone abbreviations aren’t unique to a single offset. In the first example you specified the time zone, which is more specific than the offset (+0200). In the second example, you were parsing a time from just the offset, so it could be any of the following:

Abbreviation Name Offset
CAT Central Africa Time UTC+02
CEST Central European Summer Time (Cf. HAEC) UTC+02
EET Eastern European Time UTC+02
HAEC Heure Avancée d’Europe Centrale French-language name for CEST UTC+02
IST Israel Standard Time UTC+02
KALT Kaliningrad Time UTC+02
MEST Middle European Summer Time (same zone as CEST) UTC+02
SAST South African Standard Time UTC+02
WAST West Africa Summer Time UTC+02

In your case, you know you want CEST, but if you were parsing something from a different source, how would you know that? What about when you are given a time that’s +03:00?

To solve this specific problem, however, I believe you might be looking for Time.In. Add this to your playground example:

ti2 = ti2.In(zh)

… and the output is:

2009/11/10 23:00:00 First time is : 2012-04-23 18:25:43.000000511 +0200 CEST
2009/11/10 23:00:00 Second time is: 2012-04-23 18:25:43.000000511 +0200 CEST
Program exited.

Hope this helps. See also:

2 Likes

type time.Time as new type implement json.Marshaler interface.

package main

import (
    "encoding/json"
    "fmt"
    "time"
)

type Time time.Time

func (t Time) String() string {
    return time.Time(t).Format("2006-01-02")
}

func (t Time) MarshalJSON() ([]byte, error) {
    return []byte("\"" + t.String() + "\""), nil
}

type Info struct {
    LastTime Time `json:"lastime"`
}

func main() {
    info := &Info{Time(time.Now())}
    body, err := json.Marshal(info)
    fmt.Printf("%#v\n", info)
    fmt.Println(info.LastTime)
    fmt.Println(string(body), err)
}
// &main.Info{LastTime:main.Time{wall:0xbab699fc00000000, ext:1, loc:(*time.Location)(0x5affe0)}}
// 2009-11-10
// {"lastime":"2009-11-10"} <nil>
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.