首页  >  文章  >  后端开发  >  如何在 Go 中将 YYYYMMDD 字符串转换为有效日期?

如何在 Go 中将 YYYYMMDD 字符串转换为有效日期?

Linda Hamilton
Linda Hamilton原创
2024-10-26 10:32:03305浏览

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

将 YYYYMMDD 字符串转换为 Go 中的有效日期

任务是将 YYYYMMDD 字符串转换为 Go 中的有效日期。例如,“20101011”到“2010-10-11”。

尝试和失败:

尝试使用以下两者:

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

但是,都没有产生积极的结果。

解决方案:

time 包提供了一系列预定义的布局,可以在 Time.Format() 和 Time.Parse( ) 方法。对于 YYYYMMDD 格式,对应的布局字符串为“20060102”。要获取 YYYY-MM-DD 格式,请使用布局字符串“2006-01-02”。

实现:

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

输出:

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

以上是如何在 Go 中将 YYYYMMDD 字符串转换为有效日期?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn