将未识别的格式字符串转换为日期对象

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

Converting unidentified format string into a date object

问题

我有一个日期字符串,格式如下:Tue, 03 Mar 2019 11:23:14 UTC

我想将它转换为一个日期对象,这样我就可以更改它的格式,例如转换为time.RFC822

我知道可以使用time.Parsetime.Format来实现,但问题是我不确定我所拥有的日期的确切格式,我需要在解析函数中指定一个类似于time.UnixDate但不完全相同的格式。

有没有办法将未知格式的时间字符串转换为日期对象?

英文:

I have a date string in following format Tue, 03 Mar 2019 11:23:14 UTC.

I want to convert it into a date object so I can change its format for e.g. into time.RFC822.

I understand i can use time.Parse and time.Format for this but the issue is I am not sure what exactly is the format of the date that i have which i would have to specify to a parse function, its similar to time.UnixDate but not exactly it.

Is there a way i can convert time string in unidentified format into a date object?

答案1

得分: 2

你应该查看 time 包 中的常量列表,其中包含支持的预定义时间布局。你所提供的格式已经作为 RFC1123 格式的标准布局之一得到支持。

因此,你可以简单地使用该布局来解析你的时间字符串。

package main

import (
	"fmt"
	"time"
)

func main() {
	t, _ := time.Parse(time.RFC1123, "Tue, 03 Mar 2019 11:23:14 UTC")
	fmt.Println(t)
}
英文:

You should look at the time package constants for a list of pre-defined time layouts that are supported. The format you have is already supported as one of the standard layouts as RFC1123 format.

So you can simply use that layout to parse your timestring

package main

import (
	"fmt"
	"time"
)

func main() {
	t, _ := time.Parse(time.RFC1123, "Tue, 03 Mar 2019 11:23:14 UTC")
	fmt.Println(t)
}

huangapple
  • 本文由 发表于 2023年1月4日 15:02:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75001930.html
匿名

发表评论

匿名网友

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

确定