2016-11-28 78 views
-1

我想根据一些叫做dateAdded的输入创建一个Time结构体。我的代码是这样的:在Golang中解析时间

dateAdded := "November 25, 2016" 
layout := "September 9, 2016" 
t, err := time.Parse(layout, dateAdded) 
if err != nil { 
    fmt.Println(err) 
} else { 
    fmt.Println(t) 
} 

而且我得到以下错误:解析时间“2016年11月25日”为“2016年9月9日”:无法解析“2016年11月25日”为“9月9日,

我认为解析函数不能解析每个布局,但我很好奇什么是读取日期的常用方法,并将它们解析为时间对象。

回答

1

您的布局日期错误。应该是"January 2, 2006"。如规格说明:

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

5

如果您未使用时间模块附带的预先包含的常量布局之一,则布局必须从确切的时间戳Mon Jan 2 15:04:05 -0700 MST 2006组成。注意它的每个元素都是唯一的,所以每个数字标识符都可以被自动分析。它基本上是1(月),2(天),3(小时),4(分钟),5(秒),6(年),7(时区)等。

最好使用其中一个预定义的标准布局包含在库中:

const (
     ANSIC  = "Mon Jan _2 15:04:05 2006" 
     UnixDate = "Mon Jan _2 15:04:05 MST 2006" 
     RubyDate = "Mon Jan 02 15:04:05 -0700 2006" 
     RFC822  = "02 Jan 06 15:04 MST" 
     RFC822Z  = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone 
     RFC850  = "Monday, 02-Jan-06 15:04:05 MST" 
     RFC1123  = "Mon, 02 Jan 2006 15:04:05 MST" 
     RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone 
     RFC3339  = "2006-01-02T15:04:05Z07:00" 
     RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00" 
     Kitchen  = "3:04PM" 
     // Handy time stamps. 
     Stamp  = "Jan _2 15:04:05" 
     StampMilli = "Jan _2 15:04:05.000" 
     StampMicro = "Jan _2 15:04:05.000000" 
     StampNano = "Jan _2 15:04:05.000000000" 
) 
1

您应该将它作为您提供给time.Provide的示例。它应该具有文档中描述的具体价值。

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

A playground with correct variant.