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

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

Barbara Streisand
Release: 2024-11-16 02:25:02
Original
588 people have browsed it

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

How to Parse a String into a time.Time Value in Go

When working with time in Go, it's often necessary to parse a string timestamp into a time.Time value. This task can be accomplished by leveraging the versatility of the Layout function.

Suppose you have a string timestamp in the format "20171023T183552." This format does not match any of the pre-defined layouts in the time format package. However, you can create a custom layout string to guide the parsing process.

To parse the string into a time.Time value, follow these steps:

  1. Construct a layout string that matches the input string format. In this case, the layout would be "20060102T150405." This string represents the format of the reference time when formatted using the custom layout.
  2. Utilize the Parse function to convert the string into a time.Time value. Here's an example:
s := "20171023T183552"
t, err := time.Parse("20060102T150405", s)
fmt.Println(t, err)
Copy after login

Output:

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

By generating a custom layout string that matches the input string format, you can successfully parse it into a time.Time value. This flexibility allows you to handle a wide range of time string formats in your Go applications.

The above is the detailed content of How to Parse a String into 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template