javascript - 在 Javascript 中以星期一开始和星期日结束获取一周的开始和结束

标签 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 作为开始日期和 07/06/2014 作为结束日期。有什么帮助吗?谢谢。

回答:
    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);
    }

最佳答案

您可以通过移动 getDay() 的结果,然后对结果取模来首先将其设置为星期一。

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

关于javascript - 在 Javascript 中以星期一开始和星期日结束获取一周的开始和结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24480062/

相关文章:

javascript - Sweet Alert 2括号错误和phpstorm分析

javascript - 如何遍历数组,只将以 'a' 开头的字符串添加到新数组?

javascript - 更改电脑时区后,Chrome 无法正确获取时区名称

lua 脚本中天数之后的日期

Excel VBA : Solver does not seem to optimize "over time" using a date variable?

javascript - 如何在 Alpine.js 组件中获取数据属性的值?

javascript - Angular Ajax,函数外 undefined variable

javascript - 从 .html() 中排除一些元素;在 jQuery 中

c# - 有没有一种方法可以在 C# 中获取上个月的名称和年份

javascript - 是否存在一个值 X 使得 new Date(X) 产生当前日期?