计算 2022-01-14T20:56:55Z 是否是 Go 中的有效日期时间
Work out if 2022-01-14T20:56:55Z is a valid date time in Go
我正在尝试创建一个函数来告诉我时间戳是否有效。
我的函数看起来像
// 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
}
但是,当它是一个有效的时间戳时,传入 2022-01-14T20:56:55Z
returns false。
我认为这可能与我在 time.Parse 中使用的布局有关,但我试过只使用日期,但没有成功。
您的布局与您输入的字符串不匹配,因此预计未成功解析。
docs 说:
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.
因此,您应该使用与您的输入匹配的布局。下面,我使用 RFC3339,这是您输入字符串的布局。
if _, err := time.Parse(time.RFC3339, str); err != nil {
...
}
2022-01-14T20:56:55Z
与布局不匹配 2006-01-02 15:04:05.999
因为:
- 布局需要在天后有一个空白,而不是
T
- 布局要求毫秒正好是三位数(只给出了两个
55
)
- 布局不希望指定时区。
Z
无效。
您可以将 2022-01-14T20:56:55Z
与布局 2006-01-02T15:04:05.99Z
或 2006-01-02T15:04:05Z
相匹配。或者更好,使用 .
我正在尝试创建一个函数来告诉我时间戳是否有效。
我的函数看起来像
// 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
}
但是,当它是一个有效的时间戳时,传入 2022-01-14T20:56:55Z
returns false。
我认为这可能与我在 time.Parse 中使用的布局有关,但我试过只使用日期,但没有成功。
您的布局与您输入的字符串不匹配,因此预计未成功解析。
docs 说:
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.
因此,您应该使用与您的输入匹配的布局。下面,我使用 RFC3339,这是您输入字符串的布局。
if _, err := time.Parse(time.RFC3339, str); err != nil {
...
}
2022-01-14T20:56:55Z
与布局不匹配 2006-01-02 15:04:05.999
因为:
- 布局需要在天后有一个空白,而不是
T
- 布局要求毫秒正好是三位数(只给出了两个
55
) - 布局不希望指定时区。
Z
无效。
您可以将 2022-01-14T20:56:55Z
与布局 2006-01-02T15:04:05.99Z
或 2006-01-02T15:04:05Z
相匹配。或者更好,使用