GO語言"time"包中"Parse"函數的用法及代碼示例。
用法:
func Parse(layout, value string)(Time, error)
Parse 解析格式化的字符串並返回它所代表的時間值。請參閱名為 Layout 的常量的文檔以了解如何表示格式。第二個參數必須可以使用作為第一個參數提供的格式字符串(布局)進行解析。
Time.Format 的示例詳細演示了布局字符串的工作原理,是一個很好的參考。
解析時(僅),輸入可能在秒字段之後立即包含小數秒字段,即使布局不表示其存在。在這種情況下,逗號或小數點後跟最大數字係列將被解析為小數秒。小數秒被截斷為納秒精度。
布局中省略的元素假定為零,如果不可能為零,則為一,因此解析 "3:04pm" 返回對應於 UTC 0 年 1 月 1 日 15:04:00 的時間(注意,由於年份為 0,這個時間是在零時間之前)。年份必須在 0000..9999 範圍內。檢查星期幾的語法,否則將被忽略。
對於指定兩位數年份 06 的布局,值 NN >= 69 將被視為 19NN,值 NN < 69 將被視為 20NN。
本評論的其餘部分說明了時區的處理。
在沒有時區指示符的情況下,Parse 返回 UTC 時間。
在解析具有 -0700 之類的區域偏移量的時間時,如果偏移量對應於當前位置 (Local) 使用的時區,則 Parse 在返回的時間中使用該位置和區域。否則,它將時間記錄為在一個虛構的位置,時間固定在給定的區域偏移。
當使用 MST 之類的區域縮寫解析時間時,如果區域縮寫在當前位置具有定義的偏移量,則使用該偏移量。時區縮寫"UTC" 被識別為 UTC,與位置無關。如果區域縮寫未知,Parse 將時間記錄為在具有給定區域縮寫和零偏移的虛構位置。這種選擇意味著可以使用相同的布局無損地解析和重新格式化這樣的時間,但表示中使用的確切時刻將因實際區域偏移量而異。為避免此類問題,請首選使用數字區域偏移的時間布局,或使用ParseInLocation
例子:
package main
import (
"fmt"
"time"
)
func main() {
// See the example for Time.Format for a thorough description of how
// to define the layout string to parse a time.Time value; Parse and
// Format use the same model to describe their input and output.
// longForm shows by example how the reference time would be represented in
// the desired layout.
const longForm = "Jan 2, 2006 at 3:04pm (MST)"
t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
fmt.Println(t)
// shortForm is another way the reference time would be represented
// in the desired layout; it has no time zone present.
// Note: without explicit zone, returns time in UTC.
const shortForm = "2006-Jan-02"
t, _ = time.Parse(shortForm, "2013-Feb-03")
fmt.Println(t)
// Some valid layouts are invalid time values, due to format specifiers
// such as _ for space padding and Z for zone information.
// For example the RFC3339 layout 2006-01-02T15:04:05Z07:00
// contains both Z and a time zone offset in order to handle both valid options:
// 2006-01-02T15:04:05Z
// 2006-01-02T15:04:05+07:00
t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
fmt.Println(t)
t, _ = time.Parse(time.RFC3339, "2006-01-02T15:04:05+07:00")
fmt.Println(t)
_, err := time.Parse(time.RFC3339, time.RFC3339)
fmt.Println("error", err) // Returns an error as the layout is not a valid time value
}
輸出:
2013-02-03 19:54:00 -0800 PST 2013-02-03 00:00:00 +0000 UTC 2006-01-02 15:04:05 +0000 UTC 2006-01-02 15:04:05 +0700 +0700 error parsing time "2006-01-02T15:04:05Z07:00": extra text: "07:00"
相關用法
- GO ParseAddress用法及代碼示例
- GO ParseUint用法及代碼示例
- GO ParseIP用法及代碼示例
- GO ParseMediaType用法及代碼示例
- GO ParseInt用法及代碼示例
- GO ParseCIDR用法及代碼示例
- GO ParseInLocation用法及代碼示例
- GO ParseDuration用法及代碼示例
- GO ParseFile用法及代碼示例
- GO ParseAddressList用法及代碼示例
- GO ParseBool用法及代碼示例
- GO ParseQuery用法及代碼示例
- GO ParseFloat用法及代碼示例
- GO ParsePKIXPublicKey用法及代碼示例
- GO PathUnescape用法及代碼示例
- GO PathEscape用法及代碼示例
- GO PutUvarint用法及代碼示例
- GO PlainAuth用法及代碼示例
- GO Print用法及代碼示例
- GO Pow10用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Parse。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。