如何在 JavaScript 中获取一周的第一天和最后一天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5210376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:11:20  来源:igfitidea点击:

How to get first and last day of the week in JavaScript

javascriptdate

提问by Petya petrov

I have today = new Date();object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?

我有today = new Date();对象。我需要获取本周的第一天和最后一天。我需要周日和周一的两个变体作为一周的开始和结束日。我现在对代码有点困惑。你能帮我吗?

回答by Raynos

var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6

var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();

firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"

This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.

这适用于本周的第一天 = 周日和本周的最后一天 = 周六。将它扩展到周一到周日运行是微不足道的。

Making it work with first and last days in different months is left as an exercise for the user

让它在不同月份的第一天和最后一天工作留给用户练习

回答by Bruno Lemos

Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.

请注意接受的答案,它没有将时间设置为 00:00:00 和 23:59:59,因此您可能会遇到问题。

I recommend using Moment.js to deal with dates. For your case:

我推荐使用 Moment.js 来处理日期。对于您的情况:

var startOfWeek = moment().startOf('week').toDate();
var endOfWeek   = moment().endOf('week').toDate();

This is just a small use case, it's really simple to do a lot of complex operations.

这只是一个小用例,做很多复杂的操作真的很简单。

You can see learn more here: http://momentjs.com/

您可以在此处查看更多信息:http: //momentjs.com/

回答by Vasant PADHIYAR

You can also use following lines of code to get first and last date of the week:

您还可以使用以下代码行获取一周的第一个和最后一个日期:

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

Hope it will be useful..

希望它会很有用..

回答by Olivier

Here's a quick way to get first and last day, for any start day. knowing that:

这是获取任何开始日的第一天和最后一天的快速方法。知道:

1 day = 86,400,000 milliseconds.

1 天 = 86,400,000 毫秒。

JS dates values are in milliseconds

JS 日期值以毫秒为单位

Recipe: figure out how many days you need to remove to get the your week's start day (multiply by 1 day's worth of milliseconds). All that is left after that is to add 6 days to get your end day.

食谱:计算出需要移除多少天才能获得一周的开始日(乘以 1 天的毫秒数)。之后剩下的就是添加 6 天以获得结束日。

var startDay = 1; //0=sunday, 1=monday etc.
var d = now.getDay(); //get the current day
var weekStart = new Date(now.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var weekEnd = new Date(weekStart.valueOf() + 6*86400000); //add 6 days to get last day

回答by Freewalker

The excellent (and immutable) date-fns libraryhandles this most concisely:

优秀(且不可变)的date-fns 库最简洁地处理了这个问题:

const start = startOfWeek(date);
const end = endOfWeek(date);

回答by krtek

You could do something like this

你可以做这样的事情

var today = new Date();
var startDay = 0; 
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (7 - today.getDay() - startDay) % 7);

Where startDayis a number from 0 to 6 where 0 stands for Sunday (ie 1 = Monday, 2 = Tuesday, etc).

哪里startDay是从 0 到 6 的数字,其中 0 代表星期日(即 1 = 星期一,2 = 星期二等)。

回答by Orchid

SetDatewill sets the day of the month. Using setDateduring start and end of the month,will result in wrong week

SetDate将设置月份中的日期。setDate在月初和月底使用,将导致错误的一周

var curr = new Date("08-Jul-2014"); // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)); // 06-Jul-2014
var lastday = new Date(curr.setDate(last)); //12-Jul-2014

If u setting Date is 01-Jul-2014, it will show firstday as 29-Jun-2014 and lastday as 05-Jun-2014 instead of 05-Jul-2014

如果您设置的日期是 01-Jul-2014,它将显示第一天为 29-Jun-2014,最后一天显示为 05-Jun-2014 而不是 05-Jul-2014

So overcome this issue i used

所以克服了我使用的这个问题

var curr = new Date();
day = curr.getDay();
firstday = new Date(curr.getTime() - 60*60*24* day*1000); //will return firstday (ie sunday) of the week
lastday = new Date(curr.getTime() + 60 * 60 *24 * 6 * 1000); //adding (60*60*6*24*1000) means adding six days to the firstday which results in lastday (saturday) of the week

回答by Syed Ehtsham Abbas

I recommend to use Moment.js for such cases. I had scenarios where I had to check current date time, this week, this month and this quarters date time. Above an answer helped me so I thought to share rest of the functions as well.

我建议在这种情况下使用 Moment.js。我有一些场景,我必须检查当前日期时间、本周、本月和本季度的日期时间。以上答案对我有帮助,所以我想也分享其余的功能。

Simply to get current date time in specific format

只需以特定格式获取当前日期时间

        case 'Today':
        moment().format("DD/MM/YYYY h:mm A");

        case 'This Week':
          moment().endOf('isoweek').format("DD/MM/YYYY h:mm A");

Week starts from Sunday and ends on Saturday if we simply use 'week' as parameter for endOf function but to get Sunday as the end of the week we need to use 'isoweek'.

如果我们简单地使用“week”作为 endOf 函数的参数,那么一周从星期日开始到星期六结束,但是为了让星期日作为一周的结束,我们需要使用“isoweek”。

        case 'This Month':
          moment().endOf('month').format("DD/MM/YYYY h:mm A");

        case 'This Quarter':
          moment().endOf('quarter').format("DD/MM/YYYY h:mm A");

I chose this format as per my need. You can change the format according to your requirement.

我根据需要选择了这种格式。您可以根据需要更改格式。

回答by Chris Lang

This works across year and month changes.

这适用于年和月的变化。

Date.prototype.GetFirstDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay())));
}

Date.prototype.GetLastDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
}

var today = new Date();

alert(today.GetFirstDayOfWeek());

alert(today.GetLastDayOfWeek());

回答by iach

        //get start of week; QT
    function _getStartOfWeek (date){
        var iDayOfWeek = date.getDay();
        var iDifference = date.getDate() - iDayOfWeek + (iDayOfWeek === 0 ?  -6:1);

        return new Date(date.setDate(iDifference));
    }, 

    function _getEndOfWeek(date){
        return new Date(date.setDate(date.getDate() + (7 - date.getDay()) === 7 ? 0 : (7 - date.getDay()) ));
    }, 

*current date == 30.06.2016 and monday is the first day in week.

*当前日期 == 30.06.2016 并且星期一是一周中的第一天。

It also works for different months and years. Tested with qunit suite:

它也适用于不同的月份和年份。用 qunit 套件测试:

enter image description here

在此处输入图片说明

        QUnit.module("Planung: Start of week");
    QUnit.test("Should return start of week based on current date", function (assert) {
        var startOfWeek = Planung._getStartOfWeek(new Date());
        assert.ok( startOfWeek , "returned date: "+ startOfWeek);
    });

    QUnit.test("Should return start of week based on a sunday date", function (assert) {
        var startOfWeek = Planung._getStartOfWeek(new Date("2016-07-03"));
        assert.ok( startOfWeek , "returned date: "+ startOfWeek);
    });

    QUnit.test("Should return start of week based on a monday date", function (assert) {
        var startOfWeek = Planung._getStartOfWeek(new Date("2016-06-27"));
        assert.ok( startOfWeek , "returned date: "+ startOfWeek);
    });

    QUnit.module("Planung: End of week");
    QUnit.test("Should return end of week based on current date", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date());
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on sunday date with different month", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-07-03"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on monday date with different month", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-27"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on 01-06-2016 with different month", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-01"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on 21-06-2016 with different month", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-21"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on 28-12-2016 with different month and year", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-12-28"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });
    QUnit.test("Should return end of week based on 01-01-2016 with different month and year", function (assert) {
        var endOfWeek = Planung._getEndOfWeek(new Date("2016-01-01"));
        assert.ok( endOfWeek , "returned date: "+ endOfWeek);
    });