在Go中解析日期

huangapple go评论169阅读模式
英文:

Date parsing in Go

问题

我正在尝试解析由tar生成的时间戳,例如'2011-01-19 22:15',但无法理解time.Parse的奇怪API。

以下代码会产生'parsing time "2011-01-19 22:15": month out of range'的错误提示:

package main
import (
    "fmt"
    "time"
)

func main () {
    var time , error = time.Parse("2011-01-19 22:15","2011-01-19 22:15")
    if error != nil {
        fmt.Println(error.String())
        return
    }
    fmt.Println(time)
}
英文:

I'm trying to parse a timestamp as produced by tar such as '2011-01-19 22:15' but can't work out the funky API of time.Parse.

The following produces 'parsing time "2011-01-19 22:15": month out of range'

package main
import (
    "fmt"
    "time"
    )

func main () {
    var time , error = time.Parse("2011-01-19 22:15","2011-01-19 22:15")
    if error != nil {
        fmt.Println(error.String())
        return
        }
    fmt.Println(time)
    }

答案1

得分: 39

按照Go time package 文档中的说明进行操作。

> 标准时间的格式为:
>
>
> > Mon Jan 2 15:04:05 MST 2006 (MST 表示
> > GMT-0700)
>
> 这对应的Unix时间为 1136243045。(可以将其理解为 01/02 03:04:05PM '06 -0700。)
> 如果要定义自己的格式,可以按照自己的方式编写。

例如,

package main
    
import (
	"fmt"
	"time"
)

func main() {
	t, err := time.Parse("2006-01-02 15:04", "2011-01-19 22:15")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(time.SecondsToUTC(t.Seconds()))
}

输出结果: Wed Jan 19 22:15:00 UTC 2011
英文:

Follow the instructions in the Go time package documentation.

> The standard time used
> in the layouts is:
>
>
> > Mon Jan 2 15:04:05 MST 2006 (MST is
> > GMT-0700)
>
> which is Unix time 1136243045. (Think
> of it as 01/02 03:04:05PM '06 -0700.)
> To define your own format, write down
> what the standard time would look like
> formatted your way.

For example,

package main
    
import (
	"fmt"
	"time"
)

func main() {
	t, err := time.Parse("2006-01-02 15:04", "2011-01-19 22:15")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(time.SecondsToUTC(t.Seconds()))
}

Output: Wed Jan 19 22:15:00 UTC 2011

huangapple
  • 本文由 发表于 2011年7月6日 06:38:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/6589636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定