奇怪的行为在Go.Parse功能中 [英] Strange behavior in time.Parse function in Go

查看:146
本文介绍了奇怪的行为在Go.Parse功能中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下代码片段时,主要来自 Go的时间包文档及其Parse功能示例

  package main 

import(
time
fmt


var shortForm =2006-Jan-02
t,_:= time.Parse(shortForm,2013-Feb-03 )
fmt.Println(t)

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



但是,当您更改略低于 shortForm 值,例如 2007-Jan-02 2006-Feb-02 或 2006年1月1日,它会输出错误的结果,并且输出看起来并不经常,例如 0001 -01-01 00:00:00 +0000 UTC 2013-03-01 00:00:00 +0000 UTC 2013-01-03 00:00:00 +0000 UTC



那为什么这个函数表现得这么奇怪呢?我该如何处理它?每次我使用这个函数,我应该总是将layout变量定义为 2006-Jan-02



谢谢。 .Format 函数使用layout参数中的数字来标识引用哪个日期组件:


  • 1 :month(或者可以用词语出现为 1月 / 1月

  • 2 :day

  • 3 :小时(也可以是24小时制的 15

  • 4 :分钟

  • 5 :秒

  • 6 :year(或者作为 2006 为4位数年份)

  • 7 :时区(时区代码为 MST )。


因此,当您将布局字符串从 2006-Jan-02 更改为 2006-Jan-01 时,你是在说我这个月s在时间字符串中表示两次,导致意想不到的结果。


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.

解决方案

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.

这篇关于奇怪的行为在Go.Parse功能中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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