Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang check if a data is time.Time

Tags:

types

time

go

In a if condition I'm trying to know if my data's type is time.Time.

What is the best way to get the res.Datas[i]'s data type and check it in a if loop ?

like image 294
Doby Avatar asked Oct 21 '25 03:10

Doby


1 Answers

Assuming type of res.Datas[i] is not a concrete type but an interface type (e.g. interface{}), simply use a type assertion for this:

if t, ok := res.Datas[i].(time.Time); ok {
    // it is of type time.Time
    // t is of type time.Time, you can use it so
} else {
    // not of type time.Time, or it is nil
}

If you don't need the time.Time value, you just want to tell if the interface value wraps a time.Time:

if _, ok := res.Datas[i].(time.Time); ok {
    // it is of type time.Time
} else {
    // not of type time.Time, or it is nil
}

Also note that the types time.Time and *time.Time are different. If a pointer to time.Time is wrapped, you need to check that as a different type.

like image 113
icza Avatar answered Oct 23 '25 17:10

icza