Go中的月份转换为整数

huangapple go评论100阅读模式
英文:

Month to int in Go

问题

当我调用Second()Year()等时间函数时,我得到的结果是int类型。但是当我调用Month()时,我得到的结果是Month类型。

我在在线文档中找到了以下内容:

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

.. 但是我不太理解它。

我的代码出现了以下错误,因为m不是int类型:

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

如何从Month()中获取一个int类型的值?

英文:

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

答案1

得分: 79

考虑以下代码:

var m time.Month

m 的底层类型是 int,因此可以将其转换为 int

var i int = int(m) // 通常写作 'i := int(m)'

顺便提一下:问题中出现了一个除法 m / time.Month(10)。除非你想计算某个 dekamonth 值,否则这可能是一个错误。

英文:

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 Go中的月份转换为整数

答案2

得分: 21

你必须明确将其转换为int类型:

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

在go playground中查看这个最小示例

英文:

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.

答案3

得分: 5

从技术上讲,这不是整数,但如果您想要获取类似于"2020-04-16"(2020年4月16日)的月份字符串,您可以这样做:

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

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

huangapple
  • 本文由 发表于 2013年5月22日 16:11:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/16686672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定