Home >Backend Development >Golang >How to convert a YYYYMMDD string to a valid date in Go?

How to convert a YYYYMMDD string to a valid date in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 10:32:03382browse

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:

  1. now := time.Now().Format("20101011")
  2. date, _ := time.Parse("20101011", "20101011")

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!

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