在Go语言的time.Parse函数中出现了奇怪的行为。

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

Strange behavior in time.Parse function in Go

问题

当你执行上述代码片段时,它主要是从Go的时间包文档和其Parse函数示例中衍生出来的。

然后,你可以在控制台中得到正确的结果2013-02-03 00:00:00 +0000 UTC

然而,当你稍微改变shortForm的值,比如2007-Jan-022006-Feb-022006-Jan-01,它会输出错误的结果,并且输出看起来甚至不规律,比如0001-01-01 00:00:00 +0000 UTC2013-03-01 00:00:00 +0000 UTC2013-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.Parsetime.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 as Jan / January)
  • 2: day
  • 3: hour (alternatively as 15 for 24 hour clock)
  • 4: minute
  • 5: second
  • 6: year (alternatively as 2006 for 4 digit year)
  • 7: time zone (alternatively as MST 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.

huangapple
  • 本文由 发表于 2013年9月21日 08:34:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/18927725.html
匿名

发表评论

匿名网友

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

确定