解析不完整字符串中的 Golang 时间对象

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

Parsing a golang time object from an incomplete string

问题

我有以下日期字符串:2017-09-04T04:00:00Z

我需要将这个字符串解析为golang时间,以便在我的应用程序中拥有统一的数据。以下是目前的代码:

parsedTime := "2017-09-04T04:00:00Z"
test, err := time.Parse(time.RFC3339, parsedTime)
check(err)
fmt.Println(test)

当我尝试运行程序时,我得到以下错误:

extra text: 0:00 +0000 UTC parsing time "2017-09-04T04:00:00Z"

我应该如何添加它所需要的额外文本,或者如何让解析器在Z之后停止查找?

我还尝试了以下代码:

parsedTime := "2017-09-04T04:00:00Z"
test, err := time.Parse("2006-01-02T03:04:05Z", parsedTime)
check(err)
fmt.Println(test)

这返回了以下错误:

extra text: 017-09-04T04:00:00Z
英文:

I have the following date string: 2017-09-04T04:00:00Z

I need to parse this string into a golang time in order to have uniform data across my application. Here is the code so far:

parsedTime := "2017-09-04T04:00:00Z"
test, err := time.Parse(time.RFC3339, parsedTime)
check(err)
fmt.Println(test)

I get the following error when I try to run the program:

": extra text: 0:00 +0000 UTC parsing time "2017-09-04T04:00:00Z

How can I either add the extra text that it is looking for or get the parser to stop looking after the Z?

I have also tried the following:

parsedTime := "2017-09-04T04:00:00Z"
test, err := time.Parse("2006-01-02T03:04:05Z", parsedTime)
check(err)
fmt.Println(test)

Which returns the following error:

": extra text: 017-09-04T04:00:00Z

答案1

得分: 1

你使用的两种格式都适用于当前版本的Go:https://play.golang.org/p/Typyq3Okrd

var formats = []string{
    time.RFC3339,
    "2006-01-02T03:04:05Z",
}

func main() {
    parsedTime := "2017-09-04T04:00:00Z"

    for _, format := range formats {
        if test, err := time.Parse(format, parsedTime); err != nil {
            fmt.Printf("ERROR: format %q resulted in error: %v\n", format, err)
        } else {
            fmt.Printf("format %q yielded %s\n", format, test)
        }
    }
}

你能提供一个能够演示你的问题的可工作示例吗?你可以使用Go Playground(https://play.golang.org/)来分享代码片段。

英文:

Both formats you used work with the current version of go: https://play.golang.org/p/Typyq3Okrd

var formats = []string{
	time.RFC3339,
	"2006-01-02T03:04:05Z",
}

func main() {
	parsedTime := "2017-09-04T04:00:00Z"

	for _, format := range formats {
		if test, err := time.Parse(format, parsedTime); err != nil {
			fmt.Printf("ERROR: format %q resulted in error: %v\n", format, err)
		} else {
			fmt.Printf("format %q yielded %s\n", format, test)
		}
	}
}

Can you provide a working example that demonstrates your problem? You can use the go playground for shareable snippets.

huangapple
  • 本文由 发表于 2016年3月31日 08:58:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/36322404.html
匿名

发表评论

匿名网友

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

确定