Home > Backend Development > Golang > How to Format the Current Time as a String in Go?

How to Format the Current Time as a String in Go?

DDD
Release: 2024-12-09 21:03:26
Original
617 people have browsed it

How to Format the Current Time as a String in Go?

How to Obtain Current Time as Formatted 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")
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template