将星期几字符串转换为时间。工作日值
在 Go 中,您可能会遇到需要转换表示星期几到其对应的时间。工作日值。
一种方法是使用如下数组:
<code class="go">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) }</code>
使用地图的替代方法
为了提高效率和便于查找,地图是更惯用的选择:
<code class="go">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) }</code>
其他解析选项
使用地图可以让您扩展支持的工作日以包括缩写形式:
<code class="go">for d := time.Sunday; d <= time.Saturday; d++ { name := d.String() daysOfWeek[name] = d daysOfWeek[name[:3]] = d }</code>
这可以解析完整和缩写的工作日字符串,例如“Monday”和“Mon”。
以上是如何在 Go 中将星期几字符串转换为 time.Weekday 值?的详细内容。更多信息请关注PHP中文网其他相关文章!