how can i get which day of week month starts on fr

2020-07-11 08:57发布

问题:

i have js code which stacks div's that are represanting days in month in a larger div that is actually a calendar. user can freely select month and year and i need to build calendar for that month.

for example: if this month is starting with saturday i need to first build 5 empty blocks and then start filling calendar with blocks that have number of day inside them. how can i calculate this number for given input of month and year?

回答1:

You can get the day of the week by using the getDay function of the Date object.

To get the first of the month create a new Date object:

var year = "2012";
var month = "12";
var day = new Date(year + "-" + month + "-01").getDay();
// 6 - Saturday
console.log(day);

Since you count from 1 and Monday is the first day of the week you'll also have to do this:

day = (day===0) ? 7 : day


回答2:

ES6 way:

const firstDayInMonthIndex = (
  monthIndex = new Date().getMonth(), 
  year = new Date().getFullYear()
) => (
  new Date(`${year}-${monthIndex + 1}-01`).getDay()
)