Home > Backend Development > Golang > How to Convert a Weekday String to time.Weekday in Go?

How to Convert a Weekday String to time.Weekday in Go?

Barbara Streisand
Release: 2024-10-31 10:26:02
Original
783 people have browsed it

How to Convert a Weekday String to time.Weekday in Go?

Convert Weekday String to time.Weekday

In Go, converting a day of week string to a time.Weekday value is not directly supported by the built-in time package. To address this, users often implement custom functions for the conversion.

Custom Function Using Array

One approach is to create an array mapping day of week strings to time.Weekday values. However, this method can be inefficient due to the linear search required to find the corresponding weekday.

Improved Function Using Map

A more efficient solution is to use a map instead of an array. This allows for faster lookups and more straightforward implementation. By initializing the map with key-value pairs of day of week strings and their corresponding time.Weekday values, the function can perform a direct lookup to obtain the desired time.Weekday value.

Example Implementation:

<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>
Copy after login

Testing:

<code class="go">fmt.Println(parseWeekday("Monday")) // Output: Monday <nil>
fmt.Println(parseWeekday("Friday")) // Output: Friday <nil>
fmt.Println(parseWeekday("Invalid")) // Output: Sunday invalid weekday 'Invalid'</code>
Copy after login

Extension to Parse Short Names

Additionally, the map-based approach can be extended to parse short weekday names (e.g., "Mon" for Monday) by initializing the map with both the full and short names.

Conclusion

Using a map-based approach for converting weekday strings to time.Weekday values is a recommended and idiomatic technique in Golang. It offers faster lookups and flexibility for handling both full and short weekday names.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template