Date Format Conversion in Go
In the realm of Go programming, the conversion of date formats is a common task. One may encounter the need to transform dates from one format to another, such as converting "2010-01-23 11:44:20" to "Jan 23 '10 at 11:44."
To achieve this conversion, leverage the time package's Parse and Format functions.
Using Parse and Format
The Parse function takes a reference time (e.g., "2006-01-02 15:04:05") and a date string in the format you want to convert from. This format acts as a template to decode the input string into a time.Time object.
The Format function does the opposite. It takes a time.Time object and a reference time as parameters and returns a string representing the time in the specified format.
Example Code
Below is an example code to convert the date string "2010-01-23 11:44:20" to "Jan 23 '10 at 11:44":
package main import ( "fmt" "time" ) func main() { dtstr1 := "2010-01-23 11:44:20" dt, err := time.Parse("2006-01-02 15:04:05", dtstr1) if err == nil { dtstr2 := dt.Format("Jan 2 '06 at 15:04") fmt.Println(dtstr2) // Output: Jan 23 '10 at 11:44 } else { fmt.Println(err) } }
This code will print the converted date string "Jan 23 '10 at 11:44" to the console.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3