Home > Backend Development > Golang > How to Convert a String to a `time.Time` Value in Go?

How to Convert a String to a `time.Time` Value in Go?

DDD
Release: 2024-11-23 13:29:10
Original
222 people have browsed it

How to Convert a String to a `time.Time` Value in Go?

Parsing a String as a time.Time Value

In Go, the time.Parse function allows you to convert a string representation of a time value into a time.Time object. This can be useful when working with time-stamped data or reading input from external sources.

One common format for time strings is "YYYYMMDDTHHmmSS", where "YYYY" represents the year, "MM" the month, "DD" the day, "HH" the hour, "mm" the minute, and "SS" the second. To parse a string in this format, you can use the following layout string: "20060102T150405".

For example:

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

This will output the following:

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

Note that you can use any custom layout string that matches the format of your input string. The time.Parse function provides a flexible way to convert strings into time.Time values, regardless of the specific format they are in.

The above is the detailed content of How to Convert a String to a `time.Time` Value in Go?. 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