Get the weekday from a Date object or date string using JavaScript

dpmzmdr picture dpmzmdr · Jul 31, 2013 · Viewed 37.2k times · Source

I have a date string in (yyyy-mm-dd) format, how can I get the weekday name from it?

Example:

  • For the string "2013-07-31", the output would be "Wednesday"
  • For today's date using new Date(), the output would be based on the current day of week

Answer

Samuel Liew picture Samuel Liew · Jul 31, 2013

Use this function, comes with date string validation:

If you include this function somewhere in your project,

// Accepts a Date object or date string that is recognized by the Date.parse() method
function getDayOfWeek(date) {
  const dayOfWeek = new Date(date).getDay();    
  return isNaN(dayOfWeek) ? null : 
    ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][dayOfWeek];
}

You will be able to use it anywhere easily like this:

getDayOfWeek( "2013-07-31" )
> "Wednesday"

getDayOfWeek( new Date() ) // or
getDayOfWeek( Date.now() )
> // (will return today's day. See demo jsfiddle below...)

If invalid date string is used, a null will be returned.

getDayOfWeek( "~invalid string~" );
> null

Valid date strings are based on the Date.parse() method as described in the MDN JavaScript reference.

Demo: http://jsfiddle.net/samliew/fo1nnsgp/


Of course you can also use the moment.js plugin, especially if timezones are required.