英文:
Go time.Parse() getting “month out of range” error
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我刚开始学习Go语言,正在解析一个nginx的时间格式字符串。你可以在这里查看我的代码:
package main
import (
"time"
"log"
"fmt"
)
func main(){
//nginx时间格式
nginx_time := "03/Apr/2017:08:29:05 +0800"
t,err:=time.Parse("02/Jan/2006:15:04:05 MST",nginx_time)
if err != nil {
log.Fatal(err)
}
fmt.Println(t.Format("2006-01-02 15:04:05"))
}
我收到了以下错误信息:
GOROOT=/usr/local/go
GOPATH=/usr/local/share/go:/Users/sinopex/goroot:/Users/sinopex/goroot
/usr/local/go/bin/go build -o "/private/var/folders/5b/yf1f_9lj06bfvqvcq2h9myph0000gn/T/Build 1.go and rungo" /Users/sinopex/goroot/src/github.com/sinopex/golang/example/test/1.go
"/private/var/folders/5b/yf1f_9lj06bfvqvcq2h9myph0000gn/T/Build 1.go and rungo"
2017/04/03 12:17:12 parsing time "03/Apr/2017:08:29:05 +0800": month out of range
http://stackoverflow.com/questions/ask#
Process finished with exit code 1
你有什么想法,我在做什么方面出错了吗?
谢谢。
英文:
I'm new to Go and I was parsing a nginx time format string. You can check my code here:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
package main
import (
"time"
"log"
"fmt"
)
func main(){
//nginx time format
nginx_time :="03/Apr/2017:08:29:05 +0800"
t,err:=time.Parse("02/Jan/2016:15:04:05 MST",nginx_time)
if err != nil {
log.Fatal(err)
}
fmt.Println(t.Format("2006-01-02 15:04:05"))
}
<!-- end snippet -->
I received the following error:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
GOROOT=/usr/local/go
GOPATH=/usr/local/share/go:/Users/sinopex/goroot:/Users/sinopex/goroot
/usr/local/go/bin/go build -o "/private/var/folders/5b/yf1f_9lj06bfvqvcq2h9myph0000gn/T/Build 1.go and rungo" /Users/sinopex/goroot/src/github.com/sinopex/golang/example/test/1.go
"/private/var/folders/5b/yf1f_9lj06bfvqvcq2h9myph0000gn/T/Build 1.go and rungo"
2017/04/03 12:17:12 parsing time "03/Apr/2017:08:29:05 +0800": month out of range
http://stackoverflow.com/questions/ask#
Process finished with exit code 1
<!-- end snippet -->
Any ideas on what I am doing incorrectly?
Thank you.
答案1
得分: 7
你的解析格式与参考格式和输入格式不匹配的两个地方:
-
参考格式中的年份应为
2006
-
时区偏移应该用数字而不是时区名称来指定:
-0700
所以:
t, err := time.Parse("02/Jan/2006:15:04:05 -0700", nginx_time)
play.golang: https://play.golang.org/p/enJY0VBt3a
英文:
Your parsing format does not match the reference format and the input format in 2 places:
-
The year in the reference format should be
2006
-
The timezone offset is to be specified by numbers, not by timezone name:
-0700
So:
t, err := time.Parse("02/Jan/2006:15:04:05 -0700", nginx_time)
play.golang: https://play.golang.org/p/enJY0VBt3a
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论