Home  >  Article  >  Backend Development  >  How to Convert a String Time to a Go Time Structure?

How to Convert a String Time to a Go Time Structure?

Susan Sarandon
Susan SarandonOriginal
2024-11-16 05:39:03550browse

How to Convert a String Time to a Go Time Structure?

Converting String Time to Go Time Structure

In Go, you may encounter situations where you need to convert a string time value into a time.Time structure. A common issue arises when dealing with string time values in a specific format that isn't recognized by the default time.Parse() function.

Consider a string time in the format "20171023T183552". To parse this string, we can define our own layout string based on its specific format.

Creating the Layout String

The layout string guides the conversion process by defining how the string time value should be interpreted. For the given example, the format can be described as "YYYYMMDDTHHmmSS". This means:

  • YYYY: Four-digit year
  • MM: Two-digit month
  • DD: Two-digit day
  • T: Separator of date and time
  • HH: Two-digit hour
  • mm: Two-digit minute
  • SS: Two-digit second

Parsing the String

Once the layout string is defined, we can use it with the time.Parse() function to convert the string time value into a time.Time structure.

s := "20171023T183552"
layout := "20060102T150405"
t, err := time.Parse(layout, s)
if err != nil {
    fmt.Println(err)
}

Output:

2017-10-23 18:35:52 +0000 UTC

Conclusion

By customizing the layout string, we can successfully parse string time values into time.Time structures in Go, even if their format differs from the standard options provided by the time package.

The above is the detailed content of How to Convert a String Time to a Go Time Structure?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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