Nick
Nick

Reputation: 4552

Month to int in Go

Situation:

When I call time functions like Second(), Year() etc., I get a result of tye int. But when I call Month(), I get a result of type Month.

I found the following in the online docs:

type Month int
...
func (m Month) String() string

.. but I don't quite understand it.

Problem:

My code has the following error because m is not an int:

invalid operation: m / time.Month(10) + offset (mismatched types time.Month and int)

Question:

How to get an int from Month()?

Upvotes: 60

Views: 50290

Answers (3)

ozn
ozn

Reputation: 2238

Technically this is not int but if you are trying to get string with month like "2020-04-16" (April 16,2020), you can do this:

t := time.Now()
fmt.Printf("%d-%02d-%02d", t.Year(), int(t.Month()), t.Day())

Upvotes: 7

Brainstorm
Brainstorm

Reputation: 1180

You have to explicitly convert it to an int:

var m Month = ...
var i int = int(m)

Check this minimal example in the go playground.

Upvotes: 22

zzzz
zzzz

Reputation: 91379

Considering:

var m time.Month

m's type underlying type is int, so it can be converted to int:

var i int = int(m) // normally written as 'i := int(m)'

On a side note: The question shows a division 'm / time.Month(10)'. That may be a bug unless you want to compute some dekamonth value ;-)

Upvotes: 86

Related Questions