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

huangapple go评论78阅读模式
英文:

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

问题

反射似乎对时间类型不起作用。在这里,最好的方法是什么?

package main

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

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

	// 将字符串日期解析为Go语言的时间类型
	t, _ := time.Parse("01/02/2006", stringDate)

	ts := ""

	ts = t.String()

	v := reflect.ValueOf(ts)

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

	fmt.Println(v.Type()) // 输出 "string"。我如何将其转换为time.Time类型?
}
英文:

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 ?

}

答案1

得分: 2

当你使用time.Parse时,你已经在检查stringDate是否是一个有效的日期,并将其解析为time.Time。你真正需要做的是在解析日期时检查err

示例:

stringDate := "not a date"

// 将字符串日期解析为golang时间
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())

这将打印出:

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

但是,如果提供一个有效的日期,将会打印出:

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

你可以在这里找到可工作的示例。

英文:

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

答案2

得分: 1

这似乎可以实现:

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)
}
英文:

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

huangapple
  • 本文由 发表于 2022年2月10日 19:16:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/71064129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定