How do I get the current day of the week in JavaScript?
Davide S
davide s profile pic

To get the current day of the week in JavaScript, you can use theDate object and its various methods. Here's a step-by-step guide on how to achieve this: 1. Create a newDate object:

1
2
3

   const currentDate = new Date();
   

TheDate object represents the current date and time. 2. Use thegetDay() method to retrieve the day of the week:

1
2
3

   const currentDayIndex = currentDate.getDay();
   

ThegetDay() method returns a value between 0 and 6, where 0 represents Sunday, 1 represents Monday, and so on. This value represents the index of the current day of the week. 3. Convert the day index to the corresponding day name:

1
2
3
4

   const daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
   const currentDay = daysOfWeek[currentDayIndex];
   

ThedaysOfWeek array provides the names of the days of the week corresponding to their respective indexes. By accessing the array with thecurrentDayIndex, you can obtain the name of the current day. 4. Use thecurrentDay variable: Now you can use thecurrentDay variable to access the current day of the week. For example, you can log it to the console:

1
2
3

   console.log("Current day:", currentDay);
   

The current day of the week will be displayed in the console. By following these steps, you can retrieve the current day of the week in JavaScript. Adjust the code as needed to fit your specific requirements or to incorporate the day into your application logic.