Home > Backend Development > Golang > How to Parse Time Strings in Go with Unfamiliar Formats?

How to Parse Time Strings in Go with Unfamiliar Formats?

DDD
Release: 2024-11-14 15:30:02
Original
1020 people have browsed it

How to Parse Time Strings in Go with Unfamiliar Formats?

Understanding Time String Parsing in Go

Parsing a string into a time.Time value in Go requires specifying the correct format of the string. When faced with an unfamiliar format like "20171023T183552", it's unclear how to proceed.

Fortunately, Go allows for flexible formatting by creating a custom layout string that matches the input string's structure. To parse the given string, we can use the layout "20060102T150405" which corresponds to the format: "YYYYMMDDTHHmmSS".

import (
    "fmt"
    "time"
)

func main() {
    s := "20171023T183552"
    t, err := time.Parse("20060102T150405", s)
    fmt.Println(t, err)
}
Copy after login

This code will output:

2017-10-23 18:35:52 +0000 UTC <nil>
Copy after login

This demonstrates that even for unfamiliar formats, we can define our own layouts to successfully parse strings into time.Time values.

The above is the detailed content of How to Parse Time Strings in Go with Unfamiliar Formats?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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