这是来自用户的给定输入:
年= 2011年,月= 3(3月),周= 2
我想在2011年3月的第2周用JavaScript获取日期.
例如周日6日,周一7日,周二8日,周三9日,周四10日,周五11日,周六12日
有任何想法吗?谢谢!
解决方法:
特定
var year = 2011;
var month = 3;
var week = 2;
和
var firstDateOfMonth = new Date(year, month - 1, 1); // Date: year-month-01
var firstDayOfMonth = firstDateOfMonth.getDay(); // 0 (Sun) to 6 (Sat)
var firstDateOfWeek = new Date(firstDateOfMonth); // copy firstDateOfMonth
firstDateOfWeek.setDate( // move the Date object
firstDateOfWeek.getDate() + // forward by the number of
(firstDayOfMonth ? 7 - firstDayOfMonth : 0) // days needed to go to
); // Sunday, if necessary
firstDateOfWeek.setDate( // move the Date object
firstDateOfWeek.getDate() + // forward by the number of
7 * (week - 1) // weeks required (week - 1)
);
var dateNumbersOfMonthOnWeek = []; // output array of date #s
var datesOfMonthOnWeek = []; // output array of Dates
for (var i = 0; i < 7; i++) { // for seven days...
dateNumbersOfMonthOnWeek.push( // push the date number on
firstDateOfWeek.getDate()); // the end of the array
datesOfMonthOnWeek.push( // push the date object on
new Date(+firstDateOfWeek)); // the end of the array
firstDateOfWeek.setDate(
firstDateOfWeek.getDate() + 1); // move to the next day
}
然后
> dateNumbersOfMonthOnWeek将包含该周的日期编号.
> datesOfMonthOnWeek将具有该周的日期对象.
虽然这看起来似乎对工作来说太过分了,但要使其在所有情况下都能正常工作,例如当日期数字跨越到另一个月时.不过,我确信它可以被优化为更简洁.