2016-11-28 77 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.