在星期天从星期天开始,在一周内获得天数 [英] Get the days in a Week in Javascript, Week starts on Sunday

查看:143
本文介绍了在星期天从星期天开始,在一周内获得天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是用户给出的输入:

年= 2011,月= 3(3月),周= 2

Year = 2011, Month = 3 (March), Week = 2

我想在2011年3月的第2周获得日期。

I want to get the days in week 2 of March 2011 in JavaScript.

eg星期日6日,星期一7日,星期二8日,3月9日星期三,星期四10日,星期五11日,星期六12日

e.g. Sunday 6th, Monday 7th, Tuesday 8th, Wednesday 9th, Thursday 10th, Friday 11th, Saturday 12th

任何想法?谢谢!

推荐答案

给定

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

}

then


  • 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.

这篇关于在星期天从星期天开始,在一周内获得天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆