Work out if 2022-01-14T20:56:55Z is a valid date time in Go

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

Work out if 2022-01-14T20:56:55Z is a valid date time in Go

问题

我正在尝试创建一个函数,用于判断时间戳是否有效。

我的函数如下:

// IsTimestamp 检查字符串是否包含时间戳。
func IsTimestamp(str string) bool {
    _, err := time.Parse("2006-01-02 15:04:05.999", str)
    if err != nil {
        return false
    }

    return true
}

然而,传入 2022-01-14T20:56:55Z 返回 false,而它实际上是一个有效的时间戳。

我认为这可能与我在 time.Parse 中使用的格式有关,但是我尝试过只使用日期,但没有成功。

英文:

I am attempting to create a function that tells me if a timestamp is valid or not.

My function looks like

// IsTimestamp checks if a string contains a timestamp.
func IsTimestamp(str string) bool {
	_, err := time.Parse("2006-01-02 15:04:05.999", str)
	if err != nil {
		return false
	}

	return true
}

However, passing in 2022-01-14T20:56:55Z returns false when is it a valid timestamp.

I'm thinking this might be something to do with the layout I am using in time.Parse but I've tried just using the date with no luck.

答案1

得分: 4

你的布局与输入字符串不匹配,所以预计无法成功解析。

文档中提到:

Parse函数解析一个格式化的字符串并返回它表示的时间值。请参阅名为Layout的常量的文档,了解如何表示格式。第二个参数必须可以使用作为第一个参数提供的格式字符串(布局)进行解析。

因此,你应该使用与输入相匹配的布局。下面,我使用RFC3339,这是你的输入字符串的布局。

if _, err := time.Parse(time.RFC3339, str); err != nil {
    ...
}

https://go.dev/play/p/_Q26NS2wwfy

英文:

Your layout doesn't match your input string, so it's expected that it isn't parsed successfully.

The docs say:

> Parse parses a formatted string and returns the time value it represents. See the documentation for the constant called Layout to see how to represent the format. The second argument must be parseable using the format string (layout) provided as the first argument.

Therefore, you should use a layout that's matching your input. Below, I am using RFC3339, which is the layout of your input string.

if _, err := time.Parse(time.RFC3339, str); err != nil {
    ...
}

https://go.dev/play/p/_Q26NS2wwfy

答案2

得分: 0

2022-01-14T20:56:55Z2006-01-02 15:04:05.999的格式不匹配,因为:

  • 该格式在日期后面期望有一个空格,而不是T
  • 该格式期望毫秒部分有三位数字(只给出了两位55
  • 该格式不期望指定时区,Z不是有效的。

你可以使用格式2006-01-02T15:04:05.99Z2006-01-02T15:04:05Z来匹配2022-01-14T20:56:55Z。或者更好的是,参考The Fool's answer

英文:

2022-01-14T20:56:55Z does not match the layout 2006-01-02 15:04:05.999 because:

  • the layout expects a whitespace after day, not T
  • the layout expects exactly three digits for milliseconds (only two are given 55)
  • the layout does not expect the timezone to be specified. Z is not a valid.

You can match 2022-01-14T20:56:55Z with the layout 2006-01-02T15:04:05.99Z, or 2006-01-02T15:04:05Z. Or even better, use The Fool's answer.

huangapple
  • 本文由 发表于 2022年5月12日 21:14:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/72216273.html
匿名

发表评论

匿名网友

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

确定