Get current time as formatted string in Go?

后端 未结 8 527
北荒
北荒 2021-01-30 01:15

What\'s the best way to get the current timestamp in Go and convert to string? I need both date and time in eg. YYYYMMDDhhmmss format.

相关标签:
8条回答
  • 2021-01-30 01:38

    All the other response are very miss-leading for somebody coming from google and looking for "timestamp in go"! YYYYMMDDhhmmss is not a "timestamp".

    To get the "timestamp" of a date in go (number of seconds from january 1970), the correct function is .Unix(), and it really return an integer

    0 讨论(0)
  • 2021-01-30 01:38

    As an echo to @Bactisme's response, the way one would go about retrieving the current timestamp (in milliseconds, for example) is:

    msec := time.Now().UnixNano() / 1000000
    

    Resource: https://gobyexample.com/epoch

    0 讨论(0)
  • 2021-01-30 01:40

    https://golang.org/src/time/format.go specified For parsing time 15 is used for Hours, 04 is used for minutes, 05 for seconds.

    For parsing Date 11, Jan, January is for months, 02, Mon, Monday for Day of the month, 2006 for year and of course MST for zone

    But you can use this layout as well, which I find very simple. "Mon Jan 2 15:04:05 MST 2006"

        const layout = "Mon Jan 2 15:04:05 MST 2006"
        userTimeString := "Fri Dec 6 13:05:05 CET 2019"
    
        t, _ := time.Parse(layout, userTimeString)
        fmt.Println("Server: ", t.Format(time.RFC850))
        //Server:  Friday, 06-Dec-19 13:05:05 CET
    
        mumbai, _ := time.LoadLocation("Asia/Kolkata")
        mumbaiTime := t.In(mumbai)
        fmt.Println("Mumbai: ", mumbaiTime.Format(time.RFC850))
        //Mumbai:  Friday, 06-Dec-19 18:35:05 IST
    
    

    DEMO

    0 讨论(0)
  • 2021-01-30 01:46

    Use the time.Now() function and the time.Format() method.

    t := time.Now()
    fmt.Println(t.Format("20060102150405"))
    

    prints out 20110504111515, or at least it did a few minutes ago. (I'm on Eastern Daylight Time.) There are several pre-defined time formats in the constants defined in the time package.

    You can use time.Now().UTC() if you'd rather have UTC than your local time zone.

    0 讨论(0)
  • 2021-01-30 01:50

    Use the time.Now() and time.Format() functions (as time.LocalTime() doesn't exist anymore as of Go 1.0.3)

    t := time.Now()
    fmt.Println(t.Format("20060102150405"))
    

    Online demo (with date fixed in the past in the playground, never mind)

    0 讨论(0)
  • 2021-01-30 01:53

    To answer the exact question:

    import "github.com/golang/protobuf/ptypes"
    
    Timestamp, _ = ptypes.TimestampProto(time.Now())
    
    0 讨论(0)
提交回复
热议问题