Home > Blockchain >  what is the best way to check if a string is date value?
what is the best way to check if a string is date value?

Time:02-11

Reflection does not seem to be working for time. What is the best approach here?

package main

import (
    "fmt"
    "reflect"
    "time"
)

func main() {
    stringDate := "07/26/2020"

    // parse string date to golang time
    t, _ := time.Parse("01/02/2006", stringDate)

    ts := ""

    ts = t.String()

    v := reflect.ValueOf(ts)

    fmt.Println(ts) // prints "2020-07-26 00:00:00  0000 UTC"

    fmt.Println(v.Type()) //  prints "string". How do I get this to time.Time ?

}

CodePudding user response:

When you use time.Parse you are checking already if the stringDate is a valid date and you are parsing it to time.Time. What you really need is to check for err when parsing the date.

Example:

stringDate := "not a date"

// parse string date to golang time
t, err := time.Parse("01/02/2006", stringDate)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println("Time: ", t, "Type of t: ", reflect.ValueOf(t).Type())

Which would print out

parsing time "not a date" as "01/02/2006": cannot parse "not a date" as "01"

But providing a valid date will result in printing out:

Time:  2012-03-07 00:00:00  0000 UTC Type of t:  time.Time

The working example you can find here

CodePudding user response:

This seems to do it:

package main
import "time"

func isDateValue(stringDate string) bool {
   _, err := time.Parse("01/02/2006", stringDate)
   return err == nil
}

func main() {
   ok := isDateValue("07/26/2020")
   println(ok)
}
  • Related