Help us understand the problem. What is going on with this article?

golang で日付かどうかのチェック処理

Goで日付の整合性をチェックする(コピペ用)

GoでUtilクラスを作りたかったので作成
日付のパースが成功したかどうかで判定する

package main

import (
    "fmt"
    "regexp"
    "time"
)

func main() {

    // 日付である場合
    fmt.Println(check("20190905"))
    fmt.Println(check("2019090508"))
    fmt.Println(check("20190905122001"))
    fmt.Println(check("2019-09-05"))
    fmt.Println(check("2019/09/01/12:23:59"))
    fmt.Println(check("2019/09/01/23:23:59"))
    fmt.Println(check("2000-02-29"))

    // 以下、falseが返る
    // 足りない
    fmt.Println(check("201"))
    // 存在しない日付
    fmt.Println(check("2019-09-00"))
    // 間違った閏日
    fmt.Println(check("20190229"))
    // 文字列
    fmt.Println(check("aaaaa"))
    // 時間が間違っている
    fmt.Println(check("2019/09/01/25:23:59"))
    // 0→O
    fmt.Println(check("2O19-O9-O1"))

}

// チェック処理
func check(dateStr string) bool {
    // 削除する文字列を定義
    reg := regexp.MustCompile(`[-|/|:| | ]`)

    // 指定文字を削除
    str := reg.ReplaceAllString(dateStr, "")

    // 数値の値に対してフォーマットを定義
    format := string([]rune("20060102150405")[:len(str)])

    // パース処理 → 日付ではない場合はエラー
    _, err := time.Parse(format, str)
    return err == nil
}

Goの場合はパースした時にerrが返るから、キチンとエラーハンドリングした方が安全な所もあるかもしれない
formatが特殊だから慣れが必要なのかな

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away