英文:
Strange behavior in time.Parse function in Go
问题
当你执行上述代码片段时,它主要是从Go的时间包文档和其Parse函数示例中衍生出来的。
然后,你可以在控制台中得到正确的结果2013-02-03 00:00:00 +0000 UTC
。
然而,当你稍微改变shortForm
的值,比如2007-Jan-02
、2006-Feb-02
或2006-Jan-01
,它会输出错误的结果,并且输出看起来甚至不规律,比如0001-01-01 00:00:00 +0000 UTC
、2013-03-01 00:00:00 +0000 UTC
或2013-01-03 00:00:00 +0000 UTC
。
那么为什么这个函数的行为如此奇怪?我该如何处理它?每次使用这个函数时,我是否总是要将布局变量定义为2006-Jan-02
?
谢谢。
英文:
When you execute the following code snippet, which is derived mainly from Go's time package documentation and its Parse function example:
package main
import (
"time"
"fmt"
)
var shortForm = "2006-Jan-02"
t, _ := time.Parse(shortForm, "2013-Feb-03")
fmt.Println(t)
Then, you can get the correct result, 2013-02-03 00:00:00 +0000 UTC
, in your console.
However, when you change the shortForm
value slightly, such as 2007-Jan-02
, 2006-Feb-02
, or 2006-Jan-01
, it outputs wrong results, and the output looks not even regularly, such as 0001-01-01 00:00:00 +0000 UTC
, 2013-03-01 00:00:00 +0000 UTC
, or 2013-01-03 00:00:00 +0000 UTC
.
So why does the function behave such strangely? And how can I deal with it? Every time I use the function, should I always define layout variable as 2006-Jan-02
?
Thanks.
答案1
得分: 7
time.Parse
和time.Format
函数使用布局参数中的数字来识别日期组件的含义:
1
:月份(也可以用单词表示为Jan
/January
)2
:日期3
:小时(也可以用15
表示为24小时制)4
:分钟5
:秒6
:年份(也可以用2006
表示为4位数年份)7
:时区(也可以用MST
表示为时区代码)。
因此,当你将布局字符串从2006-Jan-02
更改为2006-Jan-01
时,你实际上是在说月份在时间字符串中出现了两次,导致了意外的结果。
英文:
The time.Parse
and time.Format
functions use the numbers in the layout argument to identify which date component is referred to:
1
: month (alternatively can appear in words asJan
/January
)2
: day3
: hour (alternatively as15
for 24 hour clock)4
: minute5
: second6
: year (alternatively as2006
for 4 digit year)7
: time zone (alternatively asMST
for time zone code).
So when you change the layout string from 2006-Jan-02
to 2006-Jan-01
, you are saying that the month is represented in the time string twice, leading to unexpected results.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论