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

Linda Hamilton
Release: 2024-10-26 10:32:03
Original
312 people have browsed it

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>
Copy after login

Output:

2009-11-10 23:00:00 +0000 UTC
20091110
2009-11-10
2010-10-11 00:00:00 +0000 UTC
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!