首頁 > 後端開發 > Golang > 主體

如何在 Go 中將 YYYYMMDD 字串轉換為有效日期?

Linda Hamilton
發布: 2024-10-26 10:32:03
原創
312 人瀏覽過

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("201010111 ")
  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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!