在Golang中从毫秒转换为时间

sad*_*lil 14 json go unmarshalling

我有一些json数据,其中有一个名为lastModifed的字段包含以毫秒为单位的时间.我想用json.UnMarshaller将这些数据转换为结构类型.我用json提交了字段.但转换似乎无效.

IE:

我的Json看起来像这样:

{
   "name" : "hello",
   "lastModified" : 1438167001716
}
Run Code Online (Sandbox Code Playgroud)

和struct看起来像

type Model struct {
    Name         string    `json:"name"`
    Lastmodified time.Time `json:"lastModified"`
}
Run Code Online (Sandbox Code Playgroud)

看起来没有正确地转换时间.我怎么能从那些毫克中获得时间?

注意:lastModifiedTime的millis来自java System.currentTimeMillis();

Ron*_*Dev 25

time.Time使用RFC3339的 golang marshals to JSON中,字符串表示.所以你需要使用int64而不是time.Time自己解组你的json 并在它之后进行转换:

type Model struct {
    Name   string `json:"name"`
    Millis int64  `json:"lastModified"`
}

func (m Model) Lastmodified() time.Time {
    return time.Unix(0, m.Millis * int64(time.Millisecond))
}
Run Code Online (Sandbox Code Playgroud)

Go playground

你也可以使用上面的特殊包装time.Time并覆盖UnmarshalJSON:

type Model struct {
    Name         string   `json:"name"`
    Lastmodified javaTime `json:"lastModified"`
}

type javaTime time.Time

func (j *javaTime) UnmarshalJSON(data []byte) error {
    millis, err := strconv.ParseInt(string(data), 10, 64)
    if err != nil {
        return err
    }
    *j = javaTime(time.Unix(0, millis * int64(time.Millisecond)))
    return nil
}
Run Code Online (Sandbox Code Playgroud)

Go playground

  • 我认为[`time.Unix(0,millis*int64(time.Mllisecond))`](https://play.golang.org/p/WSGtjRPGac)更具可读性.[`time.Unix`](https://golang.org/pkg/time/#Unix)明确记录为正确处理此类输入,而不需要调用者在几秒钟内分割纳秒值. (6认同)
  • 请注意,这对公元 1678 年至 2261 年有一个隐含的有效性限制。这对于大多数情况来说都很好,但至少应该注意,因为可读性较差的解决方案没有这样的限制。 (2认同)

Cas*_*sio 19

您可以使用UnixMilli以下方法time

myTime := time.UnixMilli(myMilliseconds)
Run Code Online (Sandbox Code Playgroud)

参考: https: //pkg.go.dev/time#UnixMilli


Vad*_*lin 6

尝试这个:

func ParseMilliTimestamp(tm int64) time.Time {
    sec := tm / 1000
    msec := tm % 1000
    return time.Unix(sec, msec*int64(time.Millisecond))
}
Run Code Online (Sandbox Code Playgroud)