Home > Backend Development > Golang > How Can I Format a Go Time Stamp as a String?

How Can I Format a Go Time Stamp as a String?

Linda Hamilton
Release: 2024-12-03 05:33:09
Original
497 people have browsed it

How Can I Format a Go Time Stamp as a String?

Formatting a Time Stamp as a String in Go

When working with time-sensitive data in Go, it's often useful to format the current time as a string. This enables you to store and display the time in a human-readable and standardized format.

Solution Using time.Now() and time.Format():

The recommended approach in Go to obtain the current time and convert it to a string is to utilize the time.Now() function and the time.Format() method.

import "time"

func main() {
    t := time.Now()
    fmt.Println(t.Format("20060102150405"))
}
Copy after login

The above code will output a string representing the current time in the "YYYYMMDDhhmmss" format. This can be customized to any desired format using the pre-defined constants in the time package or by specifying a custom layout string.

Additional Options:

  • To get the current UTC time instead of the local time, use time.Now().UTC().
  • Pre-defined time formats can be found in the time package documentation.
  • For more granular control over the formatting, use the layout argument of the time.Format() method.

The above is the detailed content of How Can I Format a Go Time Stamp as a String?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template