softare development

How to Get the Day of a Given Date in JavaScript

When working with JavaScript as a software engineer, date manipulation is a common task. One of the frequently asked questions is: How do I get the day of the week for a given date? Whether you’re building a calendar app or simply displaying the day for a specific date, JavaScript provides a straightforward solution. Try the JavaScript Quiz.

In this blog post, we’ll walk through how to write a function that takes a date as input and returns the day of the week.

Understanding JavaScript’s Date Object

JavaScript has a built-in Date object that allows us to work with dates and times. It comes with many handy methods, including:

  • getDay(): Returns the day of the week as a number (0 for Sunday, 1 for Monday, and so on).
  • toLocaleDateString(): Formats a date as a string based on locale settings.

We’ll use getDay() in our function to identify the day of the week.

Writing the Function

Here’s a simple JavaScript function to get the day of the week:

function getDayOfWeek(dateString) {
  // Days of the week in an array
  const daysOfWeek = [
    "Sunday", 
    "Monday", 
    "Tuesday", 
    "Wednesday", 
    "Thursday", 
    "Friday", 
    "Saturday"
  ];

  // Parse the input string into a Date object
  const date = new Date(dateString);

  // Check if the input is a valid date
  if (isNaN(date)) {
    return "Invalid date. Please provide a valid date in the format YYYY-MM-DD.";
  }

  // Get the day index (0-6)
  const dayIndex = date.getDay();

  // Return the name of the day
  return daysOfWeek[dayIndex];
}

// Example usage
console.log(getDayOfWeek("2025-01-07")); // Output: "Tuesday"
console.log(getDayOfWeek("2024-12-25")); // Output: "Wednesday"
console.log(getDayOfWeek("invalid-date")); // Output: "Invalid date. Please provide a valid date in the format YYYY-MM-DD."

How the Function Works

  1. Array of Days: We define an array daysOfWeek that contains the names of the days, starting from Sunday.
  2. Date Parsing: The input date string is converted to a Date object using new Date(dateString).
  3. Validation: The isNaN(date) check ensures that the input is a valid date. If not, the function returns an error message.
  4. Get Day Index: The getDay() method is used to get the day of the week as a number (0 for Sunday, 6 for Saturday).
  5. Return Day Name: Using the index from getDay(), we fetch the corresponding day name from the daysOfWeek array.

Why This Approach is Useful

  1. Handles Invalid Dates: If the user provides an invalid date, the function gracefully informs them.
  2. Readable and Easy to Use: The function is simple to understand and reusable.
  3. Customizable: You can easily extend the function to include additional features like language localization.

Adding Flexibility: Displaying the Day in Other Languages

If you’d like to display the day in a different language, you can use toLocaleDateString() with the weekday option:

function getDayOfWeekLocalized(dateString, locale = "en-US") {
  const date = new Date(dateString);

  if (isNaN(date)) {
    return "Invalid date. Please provide a valid date in the format YYYY-MM-DD.";
  }

  // Use toLocaleDateString to get the day in the specified locale
  return date.toLocaleDateString(locale, { weekday: "long" });
}

// Example usage
console.log(getDayOfWeekLocalized("2025-01-07", "fr-FR")); // Output: "mardi" (Tuesday in French)
console.log(getDayOfWeekLocalized("2025-01-07", "es-ES")); // Output: "martes" (Tuesday in Spanish)

Conclusion

By using JavaScript’s powerful Date object, you can easily determine the day of the week for any date. The getDayOfWeek() function we created is simple and reliable, making it a great addition to your JavaScript toolkit. Become a competent JavaScript developer

Whether you’re building a scheduler, a calendar app, or just satisfying curiosity about a specific date, this function has you covered!

Now it’s your turn to try it out. What day of the week were you born on? Share your thoughts or questions in the comments below!

Author

Recent Posts

This Wi-Fi-enabled pizza oven can cook pizzas in just two minutes.

Introducing the Model P Smart WiFi-enabled Pizza Oven, the latest innovation in pizza-making that lets…

2 days ago

npx create-react-app is deprecated

If you’ve been developing with React for a while, chances are you’ve used npx create-react-app…

2 days ago

How to Get Started With Amazon Web Services (AWS)

Amazon Web Services (AWS) is one of the leading cloud platforms in the world, offering…

6 days ago

Apple TV+ Announces Free Streaming Weekend This January

Apple is set to make its streaming service, Apple TV+, free for all users during…

6 days ago

Hackers Inject Malicious Code into Chrome Extensions in Bold New Attack

This month, hackers successfully modified several Chrome extensions with malicious code after infiltrating admin accounts…

1 week ago

Top 10 Tech Skills to Learn in 2025

As technology continues to evolve at an unprecedented pace, staying ahead in the tech industry…

2 weeks ago