Get current time as formatted string in Go?

后端 未结 8 526
北荒
北荒 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: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.

提交回复
热议问题