LoginSignup
6
2

More than 3 years have passed since last update.

golangにおけるDateバリデーションヅラ

Posted at

その1. regexpによる正規表現を使ったバリデーション

reg.go
validater := regexp.MustCompile(`\d{4}(/\d{2}){2} \d{2}(:\d{2}){2}`)
fmt.Println(validater.MatchString("2012/12/10 12:30:45"))
// true

fmt.Println(validater.MatchString("Mon, 02 Jan 2012 12:30:45"))
// false

その2. timeによる文字列一致を使ったバリデーション

time.go
layout := "2006/01/02 15:04:05"
_, err := time.Parse(layout, "2012/12/10 12:30:45")
// err == nil にてokを確認

layoutの指定方式は magical date magical reference date を参照。
 他言語と指定形式が異なるため注意が必要ヅラ(YYYY/MM/DD等でなく指定の実値にて設定)

互いのBenchmark比較

validation_test.go
func BenchmarkRegexpPack(b *testing.B) {
    validater := regexp.MustCompile(`\d{4}(/\d{2}){2} \d{2}(:\d{2}){2}`)
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        validater.MatchString("2012/12/10 12:30:45")
    }
}

func BenchmarkTimePack(b *testing.B) {
    layout := "2006/01/02 15:04:05"
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        time.Parse(layout, "2012/12/10 12:30:45")
    }
}

// > $ go test -bench . -benchmem -benchtime 3s
// BenchmarkRegexpPack-12    20000000    286 ns/op    0 B/op    0 allocs/op
// BenchmarkTimePack-12      30000000    145 ns/op    0 B/op    0 allocs/op
6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2