Unmarshal incorrectly formatted datetime

前端 未结 2 1056
予麋鹿
予麋鹿 2020-12-28 08:51

Background

I am learning Go and I\'m trying to do some JSON unmarshaling of a datetime.

I have some JSON produced by a program I wrote in C, I am outputtin

相关标签:
2条回答
  • 2020-12-28 09:00

    You can define your own time field type that supports both formats:

    type MyTime struct {
        time.Time
    }
    
    func (self *MyTime) UnmarshalJSON(b []byte) (err error) {
        s := string(b)
    
        // Get rid of the quotes "" around the value.
        // A second option would be to include them
        // in the date format string instead, like so below: 
        //   time.Parse(`"`+time.RFC3339Nano+`"`, s) 
        s = s[1:len(s)-1]
    
        t, err := time.Parse(time.RFC3339Nano, s)
        if err != nil {
            t, err = time.Parse("2006-01-02T15:04:05.999999999Z0700", s)
        }
        self.Time = t
        return
    }
    
    type Test struct {
        Time MyTime `json:"time"`
    }
    

    Try on Go Playground

    In the example above we take the predefined format time.RFC3339Nano, which is defined like this:

    RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
    

    and remove the :

    "2006-01-02T15:04:05.999999999Z0700"
    

    This time format used by time.Parse is described here: https://golang.org/pkg/time/#pkg-constants

    Also see the documentation for time.Parse https://golang.org/pkg/time/#Parse

    P.S. The fact that the year 2006 is used in the time format strings is probably because the first version of Golang was released that year.

    0 讨论(0)
  • 2020-12-28 09:15

    You can try https://play.golang.org/p/IsUpuTKENg

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        t, err := time.Parse("2006-01-02T15:04:05.999999999Z0700", "2016-08-08T21:35:14.052975-0200")
        if err != nil {
            panic(err)
        }
        fmt.Println(t)
    }
    
    
    0 讨论(0)
提交回复
热议问题