猿问

将工作日字符串解析为 time.Weekday

我遇到了将星期几字符串转换为time.Weekday值的问题。我找不到time包中内置的任何东西。


然后我写了这个简单的函数(满足我的需要):


var daysOfWeek = [...]string{

    "Sunday",

    "Monday",

    "Tuesday",

    "Wednesday",

    "Thursday",

    "Friday",

    "Saturday",

}


func parseWeekday(v string) (time.Weekday, error) {

    for i := range daysOfWeek {

        if daysOfWeek[i] == v {

            return time.Weekday(i), nil

        }

    }


    return time.Sunday, fmt.Errorf("invalid weekday '%s'", v)

}

在 Golang 中是否有任何其他推荐或更惯用的方法来执行此转换?


谢谢!


婷婷同学_
浏览 91回答 2
2回答

Helenr

是的,使用映射而不是数组,因此查找更快更直接:var daysOfWeek = map[string]time.Weekday{    "Sunday":    time.Sunday,    "Monday":    time.Monday,    "Tuesday":   time.Tuesday,    "Wednesday": time.Wednesday,    "Thursday":  time.Thursday,    "Friday":    time.Friday,    "Saturday":  time.Saturday,}func parseWeekday(v string) (time.Weekday, error) {    if d, ok := daysOfWeek[v]; ok {        return d, nil    }    return time.Sunday, fmt.Errorf("invalid weekday '%s'", v)}测试它:fmt.Println(parseWeekday("Monday"))fmt.Println(parseWeekday("Friday"))fmt.Println(parseWeekday("invalid"))输出(在Go Playgorund上试试):Monday <nil>Friday <nil>Sunday invalid weekday 'invalid'提示:您甚至可以使用for循环来安全地初始化daysOfWeek地图,如下所示:var daysOfWeek = map[string]time.Weekday{}func init() {    for d := time.Sunday; d <= time.Saturday; d++ {        daysOfWeek[d.String()] = d    }}测试和输出是一样的。在Go Playground试试这个。这个地图解决方案的另一个不错的属性(与您的数组解决方案相比)是您可以在同一个地图中列出其他有效值,这些值可以在time.Weekday没有额外解析代码的情况下被解析成。例如,让我们也将 3 个字母的短工作日名称解析为它们的time.Weekday等价物,例如"Mon"to time.Monday。这个扩展可以用一个简单的循环来添加:var daysOfWeek = map[string]time.Weekday{}func init() {    for d := time.Sunday; d <= time.Saturday; d++ {        name := d.String()        daysOfWeek[name] = d        daysOfWeek[name[:3]] = d    }}测试它:fmt.Println(parseWeekday("Monday"))fmt.Println(parseWeekday("Friday"))fmt.Println(parseWeekday("Mon"))fmt.Println(parseWeekday("Fri"))fmt.Println(parseWeekday("invalid"))输出(在Go Playground上尝试):Monday <nil>Friday <nil>Monday <nil>Friday <nil>Sunday invalid weekday 'invalid'

翻翻过去那场雪

这看起来是这样做的:package mainimport "time"func parseWeekday(v string) (time.Weekday, error) {&nbsp; &nbsp;t, e := time.Parse("Monday 2", v + " 2")&nbsp; &nbsp;if e != nil { return 0, e }&nbsp; &nbsp;return t.Weekday(), nil}func main() {&nbsp; &nbsp;n, e := parseWeekday("Sunday")&nbsp; &nbsp;if e != nil {&nbsp; &nbsp; &nbsp; panic(e)&nbsp; &nbsp;}&nbsp; &nbsp;println(n == time.Sunday)}https://golang.org/pkg/time#Parse
随时随地看视频慕课网APP

相关分类

Go
我要回答