Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use int as month when constructing date

Tags:

go

When I supply an int as an argument to time.Date for month, it works (Example):

time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)

Why, when I try to convert a string to int and then use that variable, I get the error:

cannot use mStr (type int) as type time.Month in argument to time.Date

Example: https://play.golang.org/p/-XFNZHK476

like image 765
Mike Avatar asked Mar 21 '16 23:03

Mike


3 Answers

You have to convert the value to the proper type:

import(
    "fmt" 
    "time" 
    "strconv"
) 

func main() {
    var m, _ = strconv.Atoi("01")
     // Now convert m to type time.Month 
    fmt.Println(time.Date(2016, time.Month(m), 1, 0, 0, 0, 0, time.UTC))
}

You converted it to a type int, but the 2nd parameter of time.Date() is of type time.Month so it would give you an error that you are not using the correct type.

like image 57
amanuel2 Avatar answered Nov 10 '22 18:11

amanuel2


In the first example you're declaring the type as a time.Month, it is not an int, it is a time.Month. In the second example the type is an int. If you were to do a cast, like in this example it would work as you expect; https://play.golang.org/p/drD_7KiJu4

If in your first example you declared m as an int or just used the := operator (the implied type would be int) and you would get the same error as in the second example. Demonstrated here; https://play.golang.org/p/iWc-2Mpsly

like image 37
evanmcdonnal Avatar answered Nov 10 '22 18:11

evanmcdonnal


The Go compiler only casts constants to types on its own. Variables need to be explicitly cast.

like image 1
WeakPointer Avatar answered Nov 10 '22 18:11

WeakPointer