ArticleZip > Day Name From Date In Js

Day Name From Date In Js

Have you ever wanted to get the day of the week from a specific date in JavaScript? Maybe you need this information for scheduling tasks, displaying events, or organizing your calendar. In this article, we'll explore how you can easily extract the day name from a given date in JavaScript.

JavaScript provides a variety of built-in functions that make it effortless to work with dates. One such function is the `getDay()` method, which returns the day of the week as a number (0 for Sunday, 1 for Monday, and so on) based on a date object.

To get the day name, we first create a new `Date` object with the desired date. For example, we can create a new date object for today's date as follows:

Js

const date = new Date();

Next, we can use the `getDay()` method on this date object to get the day of the week as a number:

Js

const dayOfWeek = date.getDay();

Now, we have the day of the week as a number. To convert this number to the corresponding day name, we can use an array that maps the numbers to the respective day names:

Js

const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const dayName = days[dayOfWeek];

In this array, each index corresponds to a day of the week. By accessing the element at the index equal to the day of the week number, we can retrieve the day name in a human-readable format.

Let's put it all together with a function that takes a date as input and returns the day name:

Js

function getDayNameFromDate(inputDate) {
  const date = new Date(inputDate);
  const dayOfWeek = date.getDay();
  const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  return days[dayOfWeek];
}

// Example usage
const inputDate = "2021-10-15";
const dayName = getDayNameFromDate(inputDate);
console.log(dayName); // Output: Friday

You can now use the `getDayNameFromDate()` function to retrieve the day name from any date in the format "YYYY-MM-DD". This can be particularly useful in applications where you need to present dates in a user-friendly way or perform actions based on the day of the week.

In conclusion, getting the day name from a specific date in JavaScript is a simple task thanks to the built-in date functions provided by the language. By leveraging the `getDay()` method in conjunction with an array mapping, you can effortlessly obtain the day of the week in a readable format.