Home >Backend Development >Golang >How to Format the Current Time as a String in Go?
A common task in programming is retrieving the current date and time as a formatted string. In Go, this can be accomplished using the time package.
The time.Now() function returns the current time in Go, and the time.Format() method can be used to convert this value into a string. For instance, if you wish to obtain the current time in the format YYYYMMDDhhmmss, you can employ the following approach:
t := time.Now() formattedTime := t.Format("20060102150405")
The formattedTime variable will now hold the current time as a string in the desired format.
Alternatively, you can use the various time format constants defined within the time package. These constants provide common date and time formats:
layout := "2006-01-02T15:04:05Z" formattedTime := t.Format(layout)
Additionally, to obtain the current time in Coordinated Universal Time (UTC), you can utilize the time.Now().UTC() function before applying the Format() method.
The above is the detailed content of How to Format the Current Time as a String in Go?. For more information, please follow other related articles on the PHP Chinese website!