php editor Banana is here to introduce you to a very practical technique: convert unrecognized format strings into date objects. In development, we often encounter date strings obtained from databases or other sources, but their format does not meet our requirements. At this time, we can use PHP's date function and formatting options to convert these strings into the date objects we need for subsequent processing and operations. Next, we will explain this conversion process in detail to help you better deal with this type of problem.
I have a date string in the following format Tue, 03 Mar 2019 11:23:14 UTC
.
I want to convert it to a date object so that I can change its format, for example into time.RFC822
.
I know I can use time.Parse
and time.Format
for this, but the problem is I'm not sure what exactly the date format I have to specify to the parse function is, it Similar to time.UnixDate
but not quite it.
Is there a way to convert a time string in an unknown format into a date object?
You should look at the time package constants for supported time layouts in a predefined list. The format you have is already supported as one of the standard layouts of the rfc1123 format.
So you can simply use that layout to parse your time string
package main import ( "fmt" "time" ) func main() { t, _ := time.Parse(time.RFC1123, "Tue, 03 Mar 2019 11:23:14 UTC") fmt.Println(t) }
The above is the detailed content of Convert unrecognized format string to date object. For more information, please follow other related articles on the PHP Chinese website!