Home > Backend Development > Golang > Convert unrecognized format string to date object

Convert unrecognized format string to date object

王林
Release: 2024-02-11 11:27:08
forward
747 people have browsed it

Convert unrecognized format string to date object

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.

Question content

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?

Workaround

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)
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template