将字符串解析为time.Time值 [英] Parse string as a time.Time value

查看:113
本文介绍了将字符串解析为time.Time值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串时间,格式为20171023T183552.我没有找到任何格式来解析此字符串值.有什么办法可以将此字符串值转换为 Go time.Time吗?

I have a string time in format 20171023T183552. I didn't find any format to parse this string value. Is there any way to convert this string value to Go time.Time ?

编辑-这不是重复的问题.我知道如何解析,但是我没有意识到我们可以使用除时间格式包中列出的布局以外的任何布局.这个答案消除了我的疑惑.

Edit - This is not duplicate question. I know how to parse, but I was unaware of the fact that we can use any layout other than listed in time format package. This answer cleared my daubt.

推荐答案

这就是"YYYYMMDDTHHmmSS",因此请使用格式字符串(布局):"20060102T150405".

That is simply "YYYYMMDDTHHmmSS", so use the format string (layout): "20060102T150405".

示例:

s := "20171023T183552"
t, err := time.Parse("20060102T150405", s)
fmt.Println(t, err)

输出(在游乐场上尝试):

2017-10-23 18:35:52 +0000 UTC <nil>

time.Parse() 的文档中引用:

Quoting from doc of time.Parse():

Parse解析格式化的字符串并返回它表示的时间值.该布局通过显示参考时间的定义方式来定义格式,

Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

如果

是值,则将被解释;它用作输入格式的示例.然后,将对输入字符串进行相同的解释.

would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

因此,基本上可以使用输入可用的格式通过格式化参考时间来生成格式字符串.

So basically generate the format string by formatting the reference time using the same format your input is available in.

有关相反的方向(将time.Time转换为string),请参见

For the opposite direction (converting time.Time to string), see Golang: convert time.Time to string.

这篇关于将字符串解析为time.Time值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆