For a better user experience, at some times we may often need to display the day of the week to the user along with the date. In this article, we will see how to find the day of the week from a date using the Golang.

We need to use Golang’s time package

To find the day of the week, we need to parse the input date string into a time.Time value using the time.Parse function. This function takes two arguments i.e. a layout specifying the expected format of the date string and the date string itself.

package main

import (
	"fmt"
	"time"
)

func main() {
	dateString := "2023-06-14"
	layout := "2006-01-02"

	date, err := time.Parse(layout, dateString)
	if err != nil {
		fmt.Println("Error parsing date:", err)
		return
	}

	fmt.Println("Parsed date:", date)
}

In the above example, time.Parse function returns a time.Time value representing the parsed date. The error will be returned if there is an error during the parsing.

Find the day of the week:

Once we have the time.Time value, we can easily find the day of the week using the Weekday() provided by the time module. The Weekday() method returns a value of type time.weekday which is an integer value ranging from 0 to 6 i.e. 0 means Sunday & 6 means Saturday.

Following is the complete example:

package main

import (
	"fmt"
	"time"
)

func main() {
	dateString := "2023-06-14"
	layout := "2006-01-02"

	date, err := time.Parse(layout, dateString)
	if err != nil {
		fmt.Println("Error parsing date:", err)
		return
	}

	dayOfWeek := date.Weekday()

	fmt.Println("Day of the week:", dayOfWeek)
}

In the above example, the Weekday() method returns the integer value which is of type time.Weekday().

To print the actual day in string format, just use the Weekday().string() method as shown below.

dayOfWeekString := date.Weekday().String()
fmt.Println("Day of the week:", dayOfWeekString)

Categorized in:

Tagged in: