time.Parse 使用自定义布局
time.Parse with custom layout
我正在尝试将此字符串模式 "4-JAN-12 9:30:14"
解析为 time.Time
。
尝试了 time.Parse("2-JAN-06 15:04:05", inputString)
和许多其他方法,但无法正常工作。
我读过 http://golang.org/pkg/time/#Parse and https://gobyexample.com/time-formatting-parsing 但似乎没有这样的例子。
谢谢!
编辑:
完整代码:
type CustomTime time.Time
func (t *CustomTime) UnmarshalJSON(b []byte) error {
auxTime, err := time.Parse("2-JAN-06 15:04:05", string(b))
*t = CustomTime(auxTime)
return err
}
parsing time ""10-JAN-12 11:20:41"" as "2-JAN-06 15:04:05": cannot
parse ""24-JAN-15 10:27:44"" as "2"
不知道你做错了什么(应该post你的代码),但它真的只是一个简单的函数调用:
s := "4-JAN-12 9:30:14"
t, err := time.Parse("2-JAN-06 15:04:05", s)
fmt.Println(t, err)
输出:
2012-01-04 09:30:14 +0000 UTC <nil>
在 Go Playground 上试用。
注意 time.Parse()
returns 2 values: the parsed time.Time
value (if parsing succeeds) and an optional error
值(如果解析失败)。
请参阅以下示例,其中我故意指定了错误的输入字符串:
s := "34-JAN-12 9:30:14"
if t, err := time.Parse("2-JAN-06 15:04:05", s); err == nil {
fmt.Println("Success:", t)
} else {
fmt.Println("Failure:", err)
}
输出:
Failure: parsing time "34-JAN-12 9:30:14": day out of range
在 Go Playground 上试试。
编辑:
现在您 post 编辑了代码和错误消息,您的问题是您的输入字符串包含前导和尾随引号!
删除前导和尾随引号即可。这是你的情况:
s := `"4-JAN-12 9:30:14"`
s = s[1 : len(s)-1]
if t, err := time.Parse("2-JAN-06 15:04:05", s); err == nil {
fmt.Println("Success:", t)
} else {
fmt.Println("Failure:", err)
}
输出(在 Go Playground 上尝试):
Success: 2012-01-04 09:30:14 +0000 UTC
我正在尝试将此字符串模式 "4-JAN-12 9:30:14"
解析为 time.Time
。
尝试了 time.Parse("2-JAN-06 15:04:05", inputString)
和许多其他方法,但无法正常工作。
我读过 http://golang.org/pkg/time/#Parse and https://gobyexample.com/time-formatting-parsing 但似乎没有这样的例子。
谢谢!
编辑: 完整代码:
type CustomTime time.Time
func (t *CustomTime) UnmarshalJSON(b []byte) error {
auxTime, err := time.Parse("2-JAN-06 15:04:05", string(b))
*t = CustomTime(auxTime)
return err
}
parsing time ""10-JAN-12 11:20:41"" as "2-JAN-06 15:04:05": cannot parse ""24-JAN-15 10:27:44"" as "2"
不知道你做错了什么(应该post你的代码),但它真的只是一个简单的函数调用:
s := "4-JAN-12 9:30:14"
t, err := time.Parse("2-JAN-06 15:04:05", s)
fmt.Println(t, err)
输出:
2012-01-04 09:30:14 +0000 UTC <nil>
在 Go Playground 上试用。
注意 time.Parse()
returns 2 values: the parsed time.Time
value (if parsing succeeds) and an optional error
值(如果解析失败)。
请参阅以下示例,其中我故意指定了错误的输入字符串:
s := "34-JAN-12 9:30:14"
if t, err := time.Parse("2-JAN-06 15:04:05", s); err == nil {
fmt.Println("Success:", t)
} else {
fmt.Println("Failure:", err)
}
输出:
Failure: parsing time "34-JAN-12 9:30:14": day out of range
在 Go Playground 上试试。
编辑:
现在您 post 编辑了代码和错误消息,您的问题是您的输入字符串包含前导和尾随引号!
删除前导和尾随引号即可。这是你的情况:
s := `"4-JAN-12 9:30:14"`
s = s[1 : len(s)-1]
if t, err := time.Parse("2-JAN-06 15:04:05", s); err == nil {
fmt.Println("Success:", t)
} else {
fmt.Println("Failure:", err)
}
输出(在 Go Playground 上尝试):
Success: 2012-01-04 09:30:14 +0000 UTC