Home >Backend Development >Golang >How Do I Convert Go's `time.Time` to Custom String Formats for Database Storage?

How Do I Convert Go's `time.Time` to Custom String Formats for Database Storage?

DDD
DDDOriginal
2025-01-05 17:50:41703browse

How Do I Convert Go's `time.Time` to Custom String Formats for Database Storage?

Convert Time Formats for Database Population

When manipulating data from a database, it's often necessary to convert time values to strings. This conversion is crucial when storing values in a slice of strings. Go offers a convenient solution for this task.

Time to String Conversion

Go's time.Time type represents timestamps. To convert a time.Time value to a string, use the Time.String() method. This method formats the timestamp according to the predefined layout string: "2006-01-02 15:04:05.999999999 -0700 MST."

Custom Date Format

If you require a more specific date format, you can use the Time.Format() method. This method takes a layout string that defines the desired output format. For instance, to format a timestamp as "yyyy-MM-dd HH:mm:ss," use the layout string "2006-01-02 15:04:05."

Usage Example

Consider the example code provided:

t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))

Output

2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00

Note:

  • The output time on the Go Playground is always fixed. Run the code locally to see current date/time.
  • Time.Format() requires a reference time (in a specific predefined format) to determine the desired output format.

The above is the detailed content of How Do I Convert Go's `time.Time` to Custom String Formats for Database Storage?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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