Use int as month when constructing date
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
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.
The Go compiler only casts constants to types on its own. Variables need to be explicitly cast.