gpt4 book ai didi

go - Go 中的错误解析时间,微秒数可变

转载 作者:数据小太阳 更新时间:2023-10-29 03:13:51 31 4
gpt4 key购买 nike

我正在尝试将字符串解析为时间对象。问题是微秒项中的位数发生变化,这会破坏解析。例如,这很好用:

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)
}

但这会导致错误,因为微秒数字与布局不匹配:

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)
}

我该如何解决这个问题,以便微秒术语仍然被解析,但有多少位并不重要?

最佳答案

在亚秒级格式中使用 9 而不是零,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

来自 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")

关于go - Go 中的错误解析时间,微秒数可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43024628/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com