使用Go解析Go时间戳

Max*_*Max 10 time parsing go

Go 打印时间

time.Now().String()
Run Code Online (Sandbox Code Playgroud)

2012-12-18 06:09:18.6155554 +0200 FLEST
Run Code Online (Sandbox Code Playgroud)

要么

2009-11-10 23:00:00 +0000 UTC
Run Code Online (Sandbox Code Playgroud)

http://play.golang.org/p/8qwq9U_Ri5

我该如何解析它?

我想FLESTFinland Latvian Estonian Standard Time 我不能在这些国家,我想我可以得到所有种类的时区.我无法找到一种统一的方式或模式来解析它time.Parse

Ale*_*uer 12

虽然time.Parse()接受一个格式字符串2006-01-02 15:04:05 -0700 MST,但使用时间定义的常量之一可能更简单.

const (
    ANSIC       = "Mon Jan _2 15:04:05 2006"
    UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
    RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
    RFC822      = "02 Jan 06 15:04 MST"
    RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
    RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
    RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
    RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
    RFC3339     = "2006-01-02T15:04:05Z07:00"
    RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
    Kitchen     = "3:04PM"
    // Handy time stamps.
    Stamp      = "Jan _2 15:04:05"
    StampMilli = "Jan _2 15:04:05.000"
    StampMicro = "Jan _2 15:04:05.000000"
    StampNano  = "Jan _2 15:04:05.000000000"
)
Run Code Online (Sandbox Code Playgroud)

编辑:如果您使用字符串作为存储或编码时间的方式(例如使用限制性编码格式),您可能需要考虑使用Unix时间.这样,你可以存储一个int64(或两个,如果你保持纳秒的数量.


top*_*kip 10

package main

import (
"fmt"
"time"
)

func main() {
    fmt.Println(time.Now())
    date := "2009-11-10 23:00:00 +0000 UTC"
    t, err := time.Parse("2006-01-02 15:04:05 -0700 MST", date)
        if err != nil {
                fmt.Println("parse error", err.Error())
        }
        fmt.Println(t.Format(time.ANSIC))
}
Run Code Online (Sandbox Code Playgroud)

游乐场:http://play.golang.org/p/hvqBgtesLd

请参阅http://golang.org/src/pkg/time/format.go?s=15404:15450#L607上的源代码


Son*_*nia 5

time.String的文档给出了它使用的格式:"2006-01-02 15:04:05.999999999 -0700 MST".一开始就是使用相同的格式进行解析.

但是,时区对您来说可能是一个问题.如果必须解析您知道使用time.String生成的时间,但是在其他时区生成,则必须具有其他时区的zoneinfo.请参阅LoadLocation下的文档.如果您无法获取zoneinfo,无法将其安装在您的系统上,或者无法在某个新的未知时区失败,则time.String格式不适合您.您必须以不同的格式获取时间戳,或从字符串中删除时区并使用修改的格式解析修改的字符串.