Home  >  Article  >  Backend Development  >  How to Convert a Day of Week String to a time.Weekday Value in Go?

How to Convert a Day of Week String to a time.Weekday Value in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 20:21:03514browse

How to Convert a Day of Week String to a time.Weekday Value in Go?

Convert a Day of Week String to a time.Weekday Value

In Go, you may encounter the need to convert a string representing a day of the week to its corresponding time.Weekday value.

One approach is to use an array like so:

<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>

An Alternative Approach Using a Map

For improved efficiency and ease of lookup, a map is a more idiomatic choice:

<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>

Additional Parsing Options

Using a map allows you to extend the supported weekdays to include abbreviated forms:

<code class="go">for d := time.Sunday; d <= time.Saturday; d++ {
    name := d.String()
    daysOfWeek[name] = d
    daysOfWeek[name[:3]] = d
}</code>

This enables parsing both full and abbreviated weekday strings, e.g., "Monday" and "Mon".

The above is the detailed content of How to Convert a Day of Week String to a time.Weekday Value in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn