将Weekday字符串解析为时间

我在中发布了此实用程序github.com/icza/gox,请参见timex.ParseWeekday()


是的,使用映射而不是数组,因此查找更快,更简单:

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上尝试一下。

该map-solution的另一个不错的属性(与array- solution相比)是您可以在同一map中列出可以被解析为其他有效值的其他有效值,而time.Weekday无需其他解析代码。

例如,我们也分析了3个字母的短星期名到其time.Weekday等同,比如"Mon"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'

解决方法

我遇到了将“星期几”字符串转换为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中执行此转换吗?

谢谢!

你可能想看:
分享给朋友: