Home >Backend Development >Golang >How to convert a YYYYMMDD string to a valid date in Go?
Convert YYYYMMDD String to a Valid Date in Go
The task is to convert a YYYYMMDD string to a valid date in Go. For instance, "20101011" to "2010-10-11".
Attempt and Failure:
Attempts were made using both:
However, neither yielded positive results.
Solution:
The time package offers a range of predefined layouts that can be utilized in Time.Format() and Time.Parse() methods. For the YYYYMMDD format, the corresponding layout string is "20060102". To obtain the YYYY-MM-DD format, use the layout string "2006-01-02".
Implementation:
<code class="go">package main import ( "fmt" "time" ) func main() { now := time.Now() fmt.Println(now) // Output: 2009-11-10 23:00:00 +0000 UTC // Convert the current time to a string in YYYYMMDD format date := now.Format("20060102") fmt.Println(date) // Output: 20091110 // Convert the current time to a string in YYYY-MM-DD format date = now.Format("2006-01-02") fmt.Println(date) // Output: 2009-11-10 // Parse a string in YYYYMMDD format back into a date date2, err := time.Parse("20060102", "20101011") if err == nil { fmt.Println(date2) // Output: 2010-10-11 00:00:00 +0000 UTC } }</code>
Output:
2009-11-10 23:00:00 +0000 UTC 20091110 2009-11-10 2010-10-11 00:00:00 +0000 UTC
The above is the detailed content of How to convert a YYYYMMDD string to a valid date in Go?. For more information, please follow other related articles on the PHP Chinese website!