英文:
Converting unidentified format string into a date object
问题
我有一个日期字符串,格式如下:Tue, 03 Mar 2019 11:23:14 UTC
。
我想将它转换为一个日期对象,这样我就可以更改它的格式,例如转换为time.RFC822
。
我知道可以使用time.Parse
和time.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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论