Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Month to int in Go

Tags:

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()?

like image 260
Nick Avatar asked May 22 '13 08:05

Nick


People also ask

What does * INT mean in Golang?

In Go a pointer is represented using the * (asterisk) character followed by the type of the stored value. In the zero function xPtr is a pointer to an int . * is also used to “dereference” pointer variables. Dereferencing a pointer gives us access to the value the pointer points to.

Is there a date type in GO?

The time package in Go's standard library provides a variety of date- and time-related functions, and can be used to represent a specific point in time using the time. Time type.

How to represent date in Golang?

The Date() function in Go language is used to find Date the Time which is equivalent to yyyy-mm-dd hh:mm:ss + nsec nanoseconds in the proper time zone in the stated location.


2 Answers

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

like image 182
zzzz Avatar answered Sep 29 '22 07:09

zzzz


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.

like image 36
Brainstorm Avatar answered Sep 29 '22 08:09

Brainstorm