There are many occasions in the past where we need to work with date and time in different programs. One of the common needs is to understand what day of the week it is today. In JavaScript, by utilizing the Date
object, this task can be performed in the simplest form. However, it should be noted that working with dates in JavaScript can sometimes appear complicated.
The getDay()
method is one of the simple methods for working with dates that gives us the ability to obtain the day number of the week. This method, if no arguments or parameters are provided, will return a number from 0 (for Sunday) to 6 (for Saturday).
If you want to use this method, you must first create a Date
object. Then, by using the getDay()
method, you can easily get the day of the week. Please note that this number can vary for different languages and calendars, but for general use, it is standardized as stated above.
For example, to display the name of the week day using the getDay()
method, you can create an array that includes the names of the days of the week and access the corresponding name based on the number returned from the getDay()
method.
In summary, if you need to convert dates or work with time in more complex projects, you might consider using libraries like Moment.js or date-fns to make the work easier and have more options available.
Sample Code:
<script>
const currentDate = new Date();
const dayNumber = currentDate.getDay();
const weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
console.log("Today: " + weekDays[dayNumber]);
</script>
Code Explanation:
const currentDate = new Date();
Creates a new
Date
object to hold the current date and time. const dayNumber = currentDate.getDay();
Uses the
getDay()
method to get the day number of the week. const weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
An array including the names of the days of the week in English.
console.log("Today: " + weekDays[dayNumber]);
Displays the name of the current day in the console.