Get current time as formatted string in Go?
Solution 1:
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.
Solution 2:
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
Solution 3:
For readability, best to use the RFC constants in the time package (me thinks)
import "fmt"
import "time"
func main() {
fmt.Println(time.Now().Format(time.RFC850))
}
Solution 4:
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)
Solution 5:
Find more info in this post: Get current date and time in various format in golang
This is a taste of the different formats that you'll find in the previous post: