在Go中解析具有可变微秒数的时间时出错

huangapple go评论78阅读模式
英文:

Error parsing time in Go with variable number of microseconds

问题

我正在尝试将一个字符串解析为时间对象。问题在于微秒部分的数字位数会发生变化,这会导致解析失败。例如,下面的代码可以正常工作:

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" // 注意这里只有3位微秒数字
	layout := "2006-01-02T15:04:05.0000000Z"
	t, _ := time.Parse(layout, timeText)
	fmt.Println(t)
}

如何修复这个问题,使得微秒部分仍然可以解析,而不管有多少位数字呢?

英文:

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

得分: 13

在子秒格式中,使用9代替零,例如:

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

根据文档

// 可以通过在布局字符串中的秒值的小数点后添加一串0或9来打印小数秒。
// 如果布局数字是0,则小数秒的宽度是指定的。注意输出有一个尾随的零。
do("小数部分为0s", "15:04:05.00000", "11:06:39.12340")

// 如果布局中的小数部分是9s,则尾随的零会被省略。
do("小数部分为9s", "15:04:05.99999999", "11:06:39.1234")
英文:

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

huangapple
  • 本文由 发表于 2017年3月26日 11:22:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/43024628.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定