为什么 time.Parse 解析时间时会出现错误?

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

why does time.Parse parse the time incorrectly?

问题

我正在尝试将一个字符串解析为时间,但不幸的是,Go语言得到了错误的月份(1月份而不是6月份)。

package main

import "fmt"
import "time"

func main() {

    t := "2014-06-23T20:29:39.688+01:00"
    tc, _ := time.Parse("2006-01-02T15:04:05.000+01:00", t)
    
    fmt.Printf("t was %v and tc was %v", t, tc)

}

运行代码

英文:

I'm trying to parse a string as time with but unfortunately go gets the wrong month (January instead of June)

package main

import "fmt"
import "time"

func main() {

	t := "2014-06-23T20:29:39.688+01:00"
	tc, _ := time.Parse("2006-01-02T15:04:05.000+01:00", t)
	
	fmt.Printf("t was %v and tc was %v", t, tc)

}

Play

答案1

得分: 13

问题在于你的时区偏移在布局中定义得不正确:参考偏移是-0700。你将自己的时区偏移定义为+01:00,所以01被解释为月份,并覆盖了先前定义的部分。由于你的工作偏移也是01,它被解析为一月。

以下示例对我有效playground

package main

import "fmt"
import "time"

func main() {

    t := "2014-06-23T20:29:39.688+01:00"
    tc, _ := time.Parse("2006-01-02T15:04:05.000-07:00", t)
    
    fmt.Printf("t was %v and tc was %v", t, tc)
    
}
英文:

The problem is that your timezone offset is ill-defined in the layout: the reference offset is -0700. You defined yours as +01:00, so the 01 is interpreted as the month and erase the previously defined one. And as your working offset is 01 as well, it is parsed as january.

The following example works for me playground

package main

import "fmt"
import "time"

func main() {

    t := "2014-06-23T20:29:39.688+01:00"
    tc, _ := time.Parse("2006-01-02T15:04:05.000-07:00", t)
    
    fmt.Printf("t was %v and tc was %v", t, tc)
    
}

答案2

得分: 5

你的布局字符串是错误的。布局字符串中的数字具有特殊含义,而你使用了两次 1:一次在月份部分,一次在时区部分。你正在解析的字符串中的时区是 01:00,所以你将 1 存储到了月份中。这就解释了为什么返回的月份是一月(第一个月)。

一个修正后的布局字符串是 2006-01-02T15:04:05.000-07:00。或者,如果你愿意使用 Z 表示 UTC,可以使用 time.RFC3339 常量。

英文:

Your layout string is incorrect. The numbers in the layout string have special meanings, and you are using 1 twice: once in the month portion and once in the time zone portion. The time zone in the string you are parsing is 01:00, so you are storing 1 into the month. This explains why the returned month was January (the first month).

A corrected layout string is 2006-01-02T15:04:05.000-07:00. Or, if you're happy with using Z to represent UTC, the time.RFC3339 constant might be appropriate.

huangapple
  • 本文由 发表于 2014年6月25日 14:45:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/24401901.html
匿名

发表评论

匿名网友

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

确定