在给定的月份和年份的输入下,我如何获得星期几的哪一天开始?

问题描述:

我有js代码,这些代码将表示每月某天的div堆叠在实际上是日历的更大的div中. 用户可以*选择月份和年份,我需要为该月份建立日历.

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.

例如:如果这个月从星期六开始,我需要先建立5个空块,然后再用其中有天数的块填充日历. 如何为给定的月份和年份输入计算此数字?

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?

您可以使用

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);

由于您从1开始算起,而星期一是一周中的第一天,因此您还必须这样做:

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