Converting Dates to Various Formats in Go
Converting dates between different formats, such as changing "2010-01-23 11:44:20" to "Jan 23 '10 at 11:44," can be achieved using Go's time package.
To accomplish this, leverage the Parse and Format functions provided by the time package. These functions require a reference time in the desired format as a parameter. This format parameter defines the layout of the desired output.
For example, to convert the date "2010-01-23 11:44:20" to "Jan 23 '10 at 11:44" in Go:
package main import ( "fmt" "time" ) func main() { dtstr1 := "2010-01-23 11:44:20" dt, _ := time.Parse("2006-01-02 15:04:05", dtstr1) dtstr2 := dt.Format("Jan 2 '06 at 15:04") fmt.Println(dtstr2) // Output: Jan 23 '10 at 15:04 }
The Parse function takes the reference time format "2006-01-02 15:04:05" and the input date string "2010-01-23 11:44:20" as parameters, and returns a time.Time object representing the parsed date.
The Format function then takes the time.Time object and the reference time format "Jan 2 '06 at 15:04" as parameters, and returns the converted date string "Jan 23 '10 at 11:44."
This approach allows for easy conversion of dates between a wide range of formats by specifying the desired reference time format parameters.
The above is the detailed content of How Can I Convert Dates to Different Formats Using Go's `time` Package?. For more information, please follow other related articles on the PHP Chinese website!