从字符串获取整数月份值 [英] Get integer month value from string
问题描述
我正在从AWS解析一个cron字符串,它看起来像这样的 cron(0 7 November 13?2019)
.有没有一种干净的方法,可以使用Go的内置类型从 11月
返回到 11
? time.Month
类型允许将 int
映射到 string
,但是似乎没有相反的方法.我想念什么吗?现在,我已经编写了此代码,以获取正在使用的 map [string] int
: monthi:= getMonths()[monthName]
.>
I'm parsing a cron string from AWS that looks like this cron(0 7 13 November ? 2019)
. Is there a clean way to go from November
back to 11
using Go's built in types? The time.Month
type allows mapping int
to string
, but there doesn't seem to be a way to do the reverse. Am I missing something? For now, I've written this to get a map[string]int
that I'm using like this: monthi := getMonths()[monthName]
.
func getMonths() map[string]int {
m := make(map[string]int)
for i := 1; i < 13; i++ {
month := time.Month(i).String()
m[month] = i
}
return m
}
推荐答案
前言:我在 timex.ParseMonth()
.
这是目前最好的方法.
最好是使用包级变量,并仅填充一次地图.
Best would be to use a package level variable and populate the map only once.
通过这种方式进行人口调查更加干净和安全:
And it's much cleaner and safer to do the population this way:
var months = map[string]time.Month{}
func init() {
for i := time.January; i <= time.December; i++ {
months[i.String()] = i
}
}
测试:
for _, s := range []string{"January", "December", "invalid"} {
m := months[s]
fmt.Println(int(m), m)
}
输出(在游乐场上尝试):
1 January
12 December
0 %!Month(0)
请注意,此映射具有灵活性,您可以添加短月份名称,以映射到同一月份.例如.您还可以添加 months ["Jan"] = time.January
,因此,如果您输入的是"Jan"
,您还可以获取时间.一月
.可以通过在同一循环中将长名称切片来轻松完成此操作,例如:
Note that this map has the flexibility that you may add short month names, mapping to the same month. E.g. you may also add months["Jan"] = time.January
, so if your input is "Jan"
, you would also be able to get time.January
. This could easily be done by slicing the long name, in the same loop, for example:
for i := time.January; i <= time.December; i++ {
name := i.String()
months[name] = i
months[name[:3]] = i
}
还请注意,可以使用 time.Parse()
在布局字符串为"January"
的情况下进行解析:
Also note that it's possible to use time.Parse()
to do the parsing where the layout string is "January"
:
for _, s := range []string{"January", "December", "invalid"} {
t, err := time.Parse("January", s)
m := t.Month()
fmt.Println(int(m), m, err)
}
哪些输出(在进入游乐场上尝试):
Which outputs (try it on the Go Playground):
1 January <nil>
12 December <nil>
1 January parsing time "invalid" as "January": cannot parse "invalid" as "January"
但是简单的地图查找在性能上胜于此.
But the simple map lookup is superior to this in performance.
看到类似的问题:将Weekday字符串解析为time.Weekday
这篇关于从字符串获取整数月份值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!