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

时间:2022-10-21 10:11:09

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?

我有今天=新的日期();对象。我需要得到本周的第一天和最后一天。我需要周日和周一的两个版本作为一周的开始和结束。我现在有点困惑于代码。你能帮我吗?

16 个解决方案

#1


134  

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

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

#2


36  

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和23:59:59,这样你就会有问题。

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

我建议使用的时刻。处理日期。对于你的情况:

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/

#3


34  

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

希望它有用。

#4


15  

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

这里有一个快速的方法来获得第一天和最后一天,对于任何开始的一天。知道:

1 day = 86,400,000 milliseconds.

1天= 86400,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

#5


5  

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

周从周日开始,到周六结束,如果我们只是用“周”作为函数的结束参数,但要把周日作为周末的结束,我们需要使用“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.

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

#6


3  

SetDate will sets the day of the month. Using setDate during 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

如果你设定的日期是2014年7月01日,那么它将会显示第一天是2014年6月29日,最后一天是2014年6月05日而不是2014年7月05日

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

#7


3  

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());

#8


2  

krtek's method has some wrong,I tested this

krtek的方法有一些错误,我对此进行了测试

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

it works

它的工作原理

#9


2  

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 startDay is a number from 0 to 6 where 0 stands for Sunday (ie 1 = Monday, 2 = Tuesday, etc).

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

#10


2  

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

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

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

#11


1  

Nice suggestion but you got a small problem in lastday. You should change it to:

这个建议不错,但是你昨天遇到了一个小问题。您应该将其更改为:

lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000);

#12


1  

        //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套件测试:

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

        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);
    });

#13


1  

Although the question is seeming as obsolete I have to point out a problem.
Question: What will happen at 1st January 2016?
I think most of the above solutions calculate start of week as 27.12.2016. For this reason I think, the correct calculation should be like the below simply;

虽然这个问题似乎已经过时了,但我必须指出一个问题。问:2016年1月1日会发生什么?我认为以上的大部分解决方案都是在2016年12月27日开始。由于这个原因,我认为正确的计算应该像下面这样简单;

var d = new Date(),
    dayInMs = 1000 * 60 * 60 * 24,
    weekInMs = dayInMs * 7,
    startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate()).valueOf(),
    todayElapsedTime = d.valueOf() - startOfToday,
    dayDiff = d.getDay() * dayInMs,
    dateDiff = dayDiff + todayElapsedTime, 
    // finally
    startOfWeek = d.valueOf() - dateDiff,
    endOfWeek = startOfWeek + weekInMs - 1;

#14


1  

var dt = new Date()  //current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay-1
var wkStart = new Date(new Date(dt).setDate(dt.getDate()- lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate()+6));

This will be useful for any date scenario.

这对于任何日期场景都是有用的。

#15


0  

The moment approach worked for me for all the cases ( although i have not test the boundaries like year end , leap years ). Only Correction in the above code is the parameter is "isoWeek" , if you want to start the week from Monday.

在所有的情况下,moment方法都对我起了作用(尽管我还没有测试像year end、leap years这样的边界)。以上代码中唯一的修改是参数为“isoWeek”,如果你想从周一开始一周。

    let startOfWeek = moment().startOf("isoWeek").toDate();
    let endOfWeek = moment().endOf("isoWeek").toDate();

#16


0  

Just using pure javascript, you can use the function below to get first day and last day of a week with freely setting day for start of week.

只要使用纯javascript,您就可以使用下面的函数获得第一天和每周的最后一天,并为每周的开始*设置一天。

var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

function getFirstDayOfWeek(date, from) {
    //Default start week from 'Sunday'. You can change it yourself.
    from = from || 'Sunday'; 
    var index = weekday.indexOf(from);
    var start = index >= 0 ? index : 0;

    var d = new Date(date);
    var day = d.getDay();
    var diff = d.getDate() - day + (start > day ? start - 7 : start);
    d.setDate(diff);
    return d;
};

Last day of week is just 6 days after first day of week

上周的最后一天是一周的第一天后的六天

function getLastDayOfWeek(date, from) {
    from = from || 'Sunday';
    var index = weekday.indexOf(from);
    var start = index >= 0 ? index : 0;

    var d = new Date(date);
    var day = d.getDay();
    var diff = d.getDate() - day + (start > day ? start - 1 : 6 + start);
    d.setDate(diff);
    return d;
};

Test:

测试:

getFirstDayOfWeek('2017-10-16'); //--> Sun Oct 15 2017
getFirstDayOfWeek('2017-10-16', 'Monday'); //--> Mon Oct 16 2017
getFirstDayOfWeek('2017-10-16', 'Tuesday'); //--> Tue Oct 10 2017

#1


134  

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

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

#2


36  

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和23:59:59,这样你就会有问题。

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

我建议使用的时刻。处理日期。对于你的情况:

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/

#3


34  

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

希望它有用。

#4


15  

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

这里有一个快速的方法来获得第一天和最后一天,对于任何开始的一天。知道:

1 day = 86,400,000 milliseconds.

1天= 86400,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

#5


5  

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

周从周日开始,到周六结束,如果我们只是用“周”作为函数的结束参数,但要把周日作为周末的结束,我们需要使用“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.

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

#6


3  

SetDate will sets the day of the month. Using setDate during 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

如果你设定的日期是2014年7月01日,那么它将会显示第一天是2014年6月29日,最后一天是2014年6月05日而不是2014年7月05日

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

#7


3  

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());

#8


2  

krtek's method has some wrong,I tested this

krtek的方法有一些错误,我对此进行了测试

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

it works

它的工作原理

#9


2  

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 startDay is a number from 0 to 6 where 0 stands for Sunday (ie 1 = Monday, 2 = Tuesday, etc).

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

#10


2  

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

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

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

#11


1  

Nice suggestion but you got a small problem in lastday. You should change it to:

这个建议不错,但是你昨天遇到了一个小问题。您应该将其更改为:

lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000);

#12


1  

        //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套件测试:

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

        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);
    });

#13


1  

Although the question is seeming as obsolete I have to point out a problem.
Question: What will happen at 1st January 2016?
I think most of the above solutions calculate start of week as 27.12.2016. For this reason I think, the correct calculation should be like the below simply;

虽然这个问题似乎已经过时了,但我必须指出一个问题。问:2016年1月1日会发生什么?我认为以上的大部分解决方案都是在2016年12月27日开始。由于这个原因,我认为正确的计算应该像下面这样简单;

var d = new Date(),
    dayInMs = 1000 * 60 * 60 * 24,
    weekInMs = dayInMs * 7,
    startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate()).valueOf(),
    todayElapsedTime = d.valueOf() - startOfToday,
    dayDiff = d.getDay() * dayInMs,
    dateDiff = dayDiff + todayElapsedTime, 
    // finally
    startOfWeek = d.valueOf() - dateDiff,
    endOfWeek = startOfWeek + weekInMs - 1;

#14


1  

var dt = new Date()  //current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay-1
var wkStart = new Date(new Date(dt).setDate(dt.getDate()- lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate()+6));

This will be useful for any date scenario.

这对于任何日期场景都是有用的。

#15


0  

The moment approach worked for me for all the cases ( although i have not test the boundaries like year end , leap years ). Only Correction in the above code is the parameter is "isoWeek" , if you want to start the week from Monday.

在所有的情况下,moment方法都对我起了作用(尽管我还没有测试像year end、leap years这样的边界)。以上代码中唯一的修改是参数为“isoWeek”,如果你想从周一开始一周。

    let startOfWeek = moment().startOf("isoWeek").toDate();
    let endOfWeek = moment().endOf("isoWeek").toDate();

#16


0  

Just using pure javascript, you can use the function below to get first day and last day of a week with freely setting day for start of week.

只要使用纯javascript,您就可以使用下面的函数获得第一天和每周的最后一天,并为每周的开始*设置一天。

var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

function getFirstDayOfWeek(date, from) {
    //Default start week from 'Sunday'. You can change it yourself.
    from = from || 'Sunday'; 
    var index = weekday.indexOf(from);
    var start = index >= 0 ? index : 0;

    var d = new Date(date);
    var day = d.getDay();
    var diff = d.getDate() - day + (start > day ? start - 7 : start);
    d.setDate(diff);
    return d;
};

Last day of week is just 6 days after first day of week

上周的最后一天是一周的第一天后的六天

function getLastDayOfWeek(date, from) {
    from = from || 'Sunday';
    var index = weekday.indexOf(from);
    var start = index >= 0 ? index : 0;

    var d = new Date(date);
    var day = d.getDay();
    var diff = d.getDate() - day + (start > day ? start - 1 : 6 + start);
    d.setDate(diff);
    return d;
};

Test:

测试:

getFirstDayOfWeek('2017-10-16'); //--> Sun Oct 15 2017
getFirstDayOfWeek('2017-10-16', 'Monday'); //--> Mon Oct 16 2017
getFirstDayOfWeek('2017-10-16', 'Tuesday'); //--> Tue Oct 10 2017