Go time.Parse 无效的 ISO 日期

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

Go time.Parse Invalid ISO Date

问题

有没有办法使用time.Parse解析以下日期字符串:2023-06-06T07:04:58:278-07

我尝试使用格式2006-01-02T15:04:05:000Z07,但最后的:导致了错误。

链接:https://go.dev/play/p/y4T7meCX6D5

英文:

Is there a way to parse the following date string using time.Parse:
2023-06-06T07:04:58:278-07?

I've attempted to use the format 2006-01-02T15:04:05:000Z07, but the last : is causing an error.

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

答案1

得分: 2

请稍等,我会为您翻译这段代码。

英文:

Write a time.Parse wrapper function to accept a decimal point, decimal comma, or colon as the seconds decimal separator.

package main

import (
	"fmt"
	"strings"
	"time"
)

// Accept a decimal point, decimal comma, or colon
// as the seconds decimal separator.
func timeParse(layout, value string) (time.Time, error) {
	t, err := time.Parse(layout, value)
	if err == nil {
		return t, err
	}
	if strings.Count(value, ":") != 3 {
		return t, err
	}
	i := strings.LastIndexByte(value, ':')
	if i < 0 {
		return t, err
	}
	value2 := value[:i] + "." + value[i+1:]
	t2, err2 := time.Parse(layout, value2)
	if err2 == nil {
		return t2, err2
	}
	return t, err
}

func main() {
	inDate := "2023-06-06T07:04:58:278-07"
	parseFormat := "2006-01-02T15:04:05Z07"
	t, e := timeParse(parseFormat, inDate)
	if e != nil {
		fmt.Println(e)
	}
	fmt.Println(t)
}

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

2023-06-06 07:04:58.278 -0700 -0700

答案2

得分: 1

问题在于:不是有效的分数秒分隔符。唯一允许的分隔符是.,,正如@rocka2q所建议的那样。我相应地更改了你的示例,并成功解析了传入的日期时间。

这也得到了这两个拉取请求的确认:

如果这解决了你的问题,请告诉我,谢谢!

英文:

The issue is that : is not a valid separator for fractional seconds. The only two allowed separators are the . and the , as suggested by @rocka2q. I changed your example accordingly and I was able to parse the incoming datetime.

package main

import (
	"fmt"
	"time"
)

func main() {
	inDate := "2023-06-06T07:04:58,158-07" // it works with the comma
	// inDate := "2023-06-06T07:04:58.158-07" // it works with the dot
	// inDate := "2023-06-06T07:04:58:158-07" // ":" is not a valid separator for the fractional seconds. Only "." is allowed
	parseFormat := "2006-01-02T15:04:05.000-07"

	t, err := time.Parse(parseFormat, inDate)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(t)
}

This is also confirmed by these two Pull Requests:

Let me know if this solves your issue, thanks!

huangapple
  • 本文由 发表于 2023年6月9日 22:06:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76441045.html
匿名

发表评论

匿名网友

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

确定