简体   繁体   中英

Get which day of week a month starts on from given input of month and year

I have some JS code which stacks div's that are representing days in a month in a larger div that is actually a calendar. Users can freely select a month and year. I need to build a calendar for that month.

For example: if this month is starting with Saturday then I need to first build 5 empty blocks and then start filling the calendar with blocks that have a number of day inside them.

How can I calculate this number for the given input of month and year?

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

ES6 way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM