首页 > 文章列表 > Golang 中如何将 JSON 字符串转换为 time.Duration 类型?

Golang 中如何将 JSON 字符串转换为 time.Duration 类型?

435 2024-11-21

Golang 中如何将 JSON 字符串转换为 time.Duration 类型?

golang中将json字符串转换为time.duration类型

在go语言中,将json字符串转换为time.duration类型,可以直接将int64类型赋值给time.duration类型。

代码示例:

package main

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

type student struct {
    id     int           `json:"id"`
    gender string        `json:"gender"`
    name   string        `ison:"nane"`
    sno    string        `json:"sno"`
    time   int64         `json:"time"` // 将字符串转为 time.duration 格式
}

func main() {
    var s1 = student{
        id:     12,
        gender: "男",
        name:   "李四",
        sno:    "001",
        time:   2000, // 单位为毫秒
    }

    fmt.printf("%#vn", s1.time) // 打印的是int64类型
    fmt.printf("%vn", time.duration(s1.time)) // 转换为time.duration类型
}

输出结果:

2000
2s
来源:1730380317