go - 如何将以毫秒为单位的字符串时间(hh :mm:ss. xxx)转换为time.Time?

标签 go

基本上我有这样的时间作为一个字符串:

15:56:36.113

我想把它转换成time.Time

根据我正在阅读的内容,在使用 time.Parse() 时我不能使用毫秒。

还有其他方法可以将我的字符串转换为 time.Time 吗?

最佳答案

Package time

Format Reference Time

A decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. A decimal point followed by one or more nines represents a fractional second, printed to the given number of decimal places, with trailing zeros removed. When parsing (only), the input may contain a fractional second field immediately after the seconds field, even if the layout does not signify its presence. In that case a decimal point followed by a maximal series of digits is parsed as a fractional second.

例如,

package main

import (
    "fmt"
    "time"
)

func main() {
    t, err := time.Parse("15:04:05", "15:56:36.113")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(t)

    fmt.Println(t.Format("15:04:05.000"))

    h, m, s := t.Clock()
    ms := t.Nanosecond() / int(time.Millisecond)
    fmt.Printf("%02d:%02d:%02d.%03d\n", h, m, s, ms)
}

输出:

0000-01-01 15:56:36.113 +0000 UTC
15:56:36.113
15:56:36.113

注意:Time 类型的零值为 0000-01-01 00:00:00.000000000 UTC

关于go - 如何将以毫秒为单位的字符串时间(hh :mm:ss. xxx)转换为time.Time?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46069792/

相关文章:

oauth - 带有市场的 Admin-sdk 不起作用

go - redis中mget()的时间复杂度是多少?

arrays - 从 csv 文件加载矩阵 - golang

mysql - 如何解析0000-00-00 00 :00:00?

go - 如何将 interface{} 转换为字符串?

go - 如何理解此规范文本?

mongodb - Azure cosmosDB(mongoDB),如何在 GO lang 或通过 Shell 中禁用集合中的自动索引

validation - 检查 POST 参数的更好方法?

go - 需要与Makefile一起使用多个Go版本

mysql - Golang Gorm 错误迁移结构