如何将mysql的TIME类型转换为go的time.Duration

mysql的字段类型TIME是类似838:59:59这样的字符串,我希望在go中将它转为time.Duration以方便使用,大家有什么好办法让它们相互转换?

2021年10月27日17点32分:目前方法更新为:

func (d *Duration) Scan(v interface{}) error {
    switch vt := v.(type) {
    case []byte:
        str := strings.Replace(string(vt), ":", "h", 1)
        str = strings.Replace(str, ":", "m", 1) + "s"
        pd, err := time.ParseDuration(str)
        if err != nil {
            return err
        }
        *d = Duration(pd)
        break
    default:
        return errors.New("类型处理错误")
    }
    return nil
}
go
世界最好语言的追随者
最佳答案

如果仅是显示可以直接实现JSON转换接口,如果有存储就实现mysql的scan和value接口,若用的是xorm可以用它的自定义类型转换接口实现

2年前 评论
whitek (作者) 2年前
renxiaotu (楼主) 2年前
讨论数量: 5

如果仅是显示可以直接实现JSON转换接口,如果有存储就实现mysql的scan和value接口,若用的是xorm可以用它的自定义类型转换接口实现

2年前 评论
whitek (作者) 2年前
renxiaotu (楼主) 2年前
pardon110

mysql time类型转 int64 的毫微秒, 换而言之mysql时间字符串转16位时间戳

type Duration int64
const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)
2年前 评论
renxiaotu (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!