Skip to content

Instantly share code, notes, and snippets.

@cocoastorm
Last active November 9, 2019 00:10
Show Gist options
  • Save cocoastorm/af7e1cc0e7b55b2a00309a3ecaef6b99 to your computer and use it in GitHub Desktop.
Save cocoastorm/af7e1cc0e7b55b2a00309a3ecaef6b99 to your computer and use it in GitHub Desktop.
Dumb Golang Month "Parse"
package main
import (
"fmt"
"time"
)
func main() {
const (
input = "November 2019"
dfmt = "January 2006"
)
t, err := time.Parse(dfmt, input)
if err != nil {
panic(err)
}
fmt.Printf("Month: %d\n", t.Month())
fmt.Printf("Year: %d\n", t.Year())
}
package main
import (
"fmt"
"strings"
"time"
)
var MonthSet map[string]time.Month
func init() {
MonthSet = make(map[string]time.Month)
}
func initMonths() {
MonthSet["January"] = time.January
MonthSet["February"] = time.February
MonthSet["March"] = time.March
MonthSet["April"] = time.April
MonthSet["May"] = time.May
MonthSet["June"] = time.June
MonthSet["July"] = time.July
MonthSet["August"] = time.August
MonthSet["September"] = time.September
MonthSet["October"] = time.October
MonthSet["November"] = time.November
MonthSet["December"] = time.December
}
func parseMonth(s string) time.Month {
m, ok := MonthSet[s]
if !ok {
return time.Month(0)
}
return m
}
func main() {
initMonths()
input := "November 2019"
pieces := strings.Split(input, " ")
ms, md := pieces[0], parseMonth(pieces[0])
fmt.Printf("%s %d\n", ms, md)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment