Home >Backend Development >Golang >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 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!