【问题标题】:How to convert a string time with milliseconds (hh:mm:ss.xxx) to time.Time?如何将毫秒(hh:mm:ss.xxx)的字符串时间转换为time.Time?
【发布时间】:2017-09-06 08:00:43
【问题描述】:

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

15:56:36.113

我想把它转换成time.Time

从我读到的内容来看,我在使用 time.Parse() 时不能使用毫秒。

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

【问题讨论】:

  • 这不是重复的。它询问小数秒。

标签: go


【解决方案1】:
package main

import (
    "fmt"
    "time"
)

func main() {
    s := "15:56:36.113"
    t,_ := time.Parse("15:04:05.000", s)

    fmt.Print(t)
}

输出:

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

你可以在这里玩更多:https://play.golang.org/p/3A3e8zHQ8r

【讨论】:

    【解决方案2】:

    Package time

    格式化参考时间

    小数点后跟一个或多个零表示小数 第二,打印到给定的小数位数。一个小数点 后跟一个或多个 9 表示小数秒,打印 到给定的小数位数,删除尾随零。 解析时(仅),输入可能包含小数秒字段 紧跟在秒字段之后,即使布局没有 表示它的存在。在这种情况下,小数点后跟 最大数字系列被解析为小数秒。

    例如,

    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
    

    注意:时间类型的零值是0000-01-01 00:00:00.000000000 UTC

    【讨论】:

      猜你喜欢
      • 2020-11-23
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多