user2703728
user2703728

Reputation:

Get the week day from a given date

I am writing my own calendar plugin but I am struggling to get the day of the week for a given date.

Lets say I have the year - 1905, the month - 4 and the day - 23. Is there any way at all that I could use this data - smash it together in a better format say YYYY/DD/MM and use this to calculate the day of the week - I was hoping to find some Gregorian calendar methods like in PHP but I am yet to find any.

Sorry if this has been asked before but I could only find questions using new Date for todays day of the week.

Upvotes: 0

Views: 2598

Answers (1)

RobG
RobG

Reputation: 147363

Construct a date object and ask it what day it is:

// Note months are zero indexed so May is 4, not 5
var d = new Date(1905, 4, 23).getDay(); // 2

Which you can turn into a function:

function getDay(y, m, d) {
  var days = ['Sunday','Monday','Tuesday',
     'Wednesday','Thursday','Friday','Saturday'];
 var d = new Date(y, --m, d);
 return d && days[d.getDay()];
}

// What day was 23 May, 1905?
console.log(getDay(1905,5,23)); // Tuesday

Edit

Note that these types of functions will convert two digit years into 20th century dates, e.g.

var d = new Date(5, 4, 23) // 23 May, 1905

and they don't check that the values are valid dates:

var d = new Date(5, 16, 23) // 23 May, 1906

If you don't want that, you have to construct the date differently and check the values:

// Create a generic date object
var d = new Date();

// Set the values for 23 May, 0005
// This way doesn't convert 5 to 1905
d.setFullYear(5, 4, 23);

// Check at least 2 values in the date are the same as the input
// The easiest to check are year and date
if (d.getFullYear() == 5 && d.getDate() == 23) {  
  console.log(d + 'is a valid date!');
}

You can create a separate function based on the above to create dates that returns either a date object or NaN if the values aren't valid (and honours two digit years).

Upvotes: 3

Related Questions