从毫秒转换为 Golang 中的时间

Convert to time in Golang from milliseconds

我有一些 json 数据,其中有一个名为 lastModifed 的字段包含以毫秒为单位的时间。我想将此数据转换为具有 json.UnMarshaller 的结构类型。我已经用 json 字段映射了字段。但是转换似乎不起作用。

IE :

我的 Json 看起来像这样:

{
   "name" : "hello",
   "lastModified" : 1438167001716
}

和结构看起来像

type Model struct {
    Name         string    `json:"name"`
    Lastmodified time.Time `json:"lastModified"`
}

看起来没有正确转换时间。我怎样才能从那些毫秒得到时间??

注意:lastModifiedTime 的毫秒数来自 java System.currentTimeMillis();

在 golang 中 time.Time 使用 RFC3339 字符串表示法编组到 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))
}

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
}

Go playground

试试这个:

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

您可以在time中使用UnixMilli方法:

myTime := time.UnixMilli(myMilliseconds)

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