[英]time.Parse with custom layout
I'm trying to parse this string pattern "4-JAN-12 9:30:14"
into a time.Time
. 我想这个字符串模式解析
"4-JAN-12 9:30:14"
到time.Time
。
Tried time.Parse("2-JAN-06 15:04:05", inputString)
and many others but cannot get it working. 尝试过
time.Parse("2-JAN-06 15:04:05", inputString)
和许多其他方法,但无法使其正常工作。
I've read http://golang.org/pkg/time/#Parse and https://gobyexample.com/time-formatting-parsing but it seems there aren't any examples like this. 我已经阅读了http://golang.org/pkg/time/#Parse和https://gobyexample.com/time-formatting-parsing,但似乎没有这样的例子。
Thanks! 谢谢!
Edit: full code: 编辑:完整代码:
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"
将时间““ 10-JAN-12 11:20:41”“解析为” 2-JAN-06 15:04:05“:无法将”“ 24-JAN-15 10:27:44”“解析为” 2“
Don't know what you did wrong (should post your code), but it is really just a simple function call: 不知道您做错了什么(应该发布您的代码),但这实际上只是一个简单的函数调用:
s := "4-JAN-12 9:30:14"
t, err := time.Parse("2-JAN-06 15:04:05", s)
fmt.Println(t, err)
Outputs: 输出:
2012-01-04 09:30:14 +0000 UTC <nil>
Try it on the Go Playground . 在Go Playground上尝试一下。
Note that time.Parse()
returns 2 values: the parsed time.Time
value (if parsing succeeds) and an optional error
value (if parsing fails). 请注意,
time.Parse()
返回2个值:解析的time.Time
值(如果解析成功)和可选的error
值(如果解析失败)。
See the following example where I intentionally specify a wrong input string: 请参阅以下示例,在此示例中,我有意指定了错误的输入字符串:
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)
}
Output: 输出:
Failure: parsing time "34-JAN-12 9:30:14": day out of range
Try it on the Go Playground . 在Go Playground上尝试一下。
EDIT: 编辑:
Now that you posted code and error message, your problem is that your input string contains a leading and trailing quotation mark! 现在,您已经发布了代码和错误消息,您的问题是输入字符串包含引号和尾部的引号!
Remove the leading and trailing quotation mark and it will work. 删除开头和结尾的引号,它将起作用。 This is your case:
这是你的情况:
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)
}
Output (try it on the Go Playground ): 输出(在Go Playground上尝试):
Success: 2012-01-04 09:30:14 +0000 UTC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.