这是来自用户的给定输入:
Here's the given input from the user:
年 = 2011,月 = 3(三月),周 = 2
Year = 2011, Month = 3 (March), Week = 2
我想用 JavaScript 获取 2011 年 3 月第 2 周的天数.
I want to get the days in week 2 of March 2011 in JavaScript.
例如6日星期日、7日星期一、8日星期二、9日星期三、10日星期四、11日星期五、12日星期六
e.g. Sunday 6th, Monday 7th, Tuesday 8th, Wednesday 9th, Thursday 10th, Friday 11th, Saturday 12th
有什么想法吗?谢谢!
推荐答案Given
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 将包含该周的日期对象.
- dateNumbersOfMonthOnWeek will have the date numbers of that week.
- datesOfMonthOnWeek will have the date objects of that week.
虽然这对于这项工作来说似乎有点矫枉过正,但要使其在所有情况下都能正常工作,例如当日期数字跨越到另一个月份时,这其中的大部分内容是必不可少的.不过,我相信它可以优化为不那么冗长.
While this may seem like it is overkill for the job, much of this is required to make it work in all situations, like when the date numbers cross over to another month. I'm sure it could be optimised to be less verbose, though.
更多推荐
在 Javascript 中获取一周中的天数,一周从星期日开始
发布评论