问题
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
}
回答1:
Foreword: I released this utility in github.com/icza/gox, see timex.ParseMonth().
That is currently the best approach.
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
}
}
Testing it:
for _, s := range []string{"January", "December", "invalid"} {
m := months[s]
fmt.Println(int(m), m)
}
Output (try it on the Go Playground):
1 January
12 December
0 %!Month(0)
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
}
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.
See similar question: Parse Weekday string into time.Weekday
来源:https://stackoverflow.com/questions/59681199/get-integer-month-value-from-string