dtp87205 2017-03-26 03:22
浏览 47
已采纳

Go中的错误解析时间,具有可变的微秒数

I'm trying to parse a string into a time object. The issue is that the number of digits in the microseconds term changes, which breaks the parsing. For example, this works fine:

package main

import (
    "fmt"
    "time"
)

func main() {
    timeText := "2017-03-25T10:01:02.1234567Z"
    layout := "2006-01-02T15:04:05.0000000Z"
    t, _ := time.Parse(layout, timeText)
    fmt.Println(t)
}

But this causes an error, because the number of microseconds digits doesn't match the layout:

package main

import (
    "fmt"
    "time"
)

func main() {
    timeText := "2017-03-25T10:01:02.123Z" // notice only 3 microseconds digits here
    layout := "2006-01-02T15:04:05.0000000Z"
    t, _ := time.Parse(layout, timeText)
    fmt.Println(t)
}

How do I fix this so that the microseconds term is still parsed, but it doesn't matter how many digits there are?

  • 写回答

1条回答 默认 最新

  • douhui9631 2017-03-26 03:39
    关注

    Use 9s instead of zeros in the subsecond format, for example:

    timeText := "2017-03-25T10:01:02.1234567Z"
    layout := "2006-01-02T15:04:05.99Z"
    t, _ := time.Parse(layout, timeText)
    fmt.Println(t) //prints 2017-03-25 10:01:02.1234567 +0000 UTC
    

    From the docs:

    // Fractional seconds can be printed by adding a run of 0s or 9s after
    // a decimal point in the seconds value in the layout string.
    // If the layout digits are 0s, the fractional second is of the specified
    // width. Note that the output has a trailing zero.
    do("0s for fraction", "15:04:05.00000", "11:06:39.12340")
    
    // If the fraction in the layout is 9s, trailing zeros are dropped.
    do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大