从星期一开始到星期日结束,在Javascript中开始和结束一周

时间:2014-06-29 20:39:22

标签: javascript date

    function getStartAndEndOfWeek(date) {

        var curr = date ? new Date(date) : new Date();
        var first = curr.getDate() - curr.getDay(); 

        var firstday = new Date(curr.setDate(first));
        var lastday = new Date(curr.setDate(firstday.getDate() + 6));

        return [firstday, lastday];

    }

我无法将周开始设为周一。上面的代码将第一天作为星期日。此外,如果我们添加第一加一,它将给星期一作为开始,但问题是在哪里可以说(06/29/2014,星期日)是输入,它应该返回(06/23/2014作为开始和06 / 29/2014)结束。我们怎样才能做到这一点?如果我添加"第一个+ 1"它将06/30/2014作为开始日期和2014年6月7日作为结束日期返回。有帮助吗?感谢。

答案:

    function getStartAndEndOfWeek(date) {

        //Calculating the starting point

        var curr = date ? new Date(date) : new Date();
        var first = curr.getDate() - dayOfWeek(curr);

        var firstday, lastday;

        if (first < 1) {
            //Get prev month and year
            var k = new Date(curr.valueOf());
            k.setDate(1);
            k.setMonth(k.getMonth() - 1);
            var prevMonthDays = new Date(k.getFullYear(), (k.getMonth() + 1), 0).getDate();

            first = prevMonthDays - (dayOfWeek(curr) - curr.getDate());
            firstday = new Date(k.setDate(first));
            lastday = new Date(k.setDate(first + 6));
        } else {
            // First day is the day of the month - the day of the week
            firstday = new Date(curr.setDate(first));
            lastday = new Date(curr.setDate(first + 6));
        }

        return [firstday, lastday];            
    }

    function dayOfWeek(date, firstDay) {
        var daysOfWeek = {
            sunday: 0,
            monday: 1,
            tuesday: 2,
            wednesday: 3,
            thursday: 4,
            friday: 5,
            saturday: 6,
        };
        firstDay = firstDay || "monday";
        var day = date.getDay() - daysOfWeek[firstDay];
        return (day < 0 ? day + 7 : day);
    }

2 个答案:

答案 0 :(得分:4)

如何制作一个简单的方法让您轻松操控一周的第一天:

(function() {
  var original = Date.prototype.getDay;
  var daysOfWeek = {
    sunday: 0,
    monday: 1,
    tuesday: 2,
    wednesday: 3,
    thursday: 4,
    friday: 5,
    saturday: 6,
  };

  Date.prototype.getDay = function(weekBegins) {
    weekBegins = (weekBegins || "sunday").toLowerCase();
    return (original.apply(this) + 7 - daysOfWeek[weekBegins]) % 7;
  };
})();

然后你可以简单地使用:

var first = curr.getDate() - curr.getDay("monday"),
    last  = first + 6;

答案 1 :(得分:2)

您可以先调整getDay()的结果,然后取结果的模数,先设置为星期一。

var first = curr.getDate() - ((curr.getDay() + 6) % 7);