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


94

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

Answers:


186
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"

这适用于本周的第一天=本周的星期日,最后一天=本周的星期六。将其延长到周一至周日是微不足道的。

用户可以将其与不同月份的头几天和最后一天一起使用作为练习


谢谢,但是当第一天是星期一时,我该如何做呢?
JuanPablo 2012年

4
var first = curr.getDate() - curr.getDay() +1;
JuanPablo 2012年

40
要在不同的月份使用它var lastday = new Date(curr.setDate(first.getDate()+6)).toUTCString();
理查德N

2
与@Rayons答案类似的代码,但即使在其他月份和年份中也可以使用, var curr = new Date('2014-10-01T00:00:00'); // 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 firstday = new Date(curr.setDate(first)).toUTCString(); lastday = new Date(curr.setDate(curr.getDate()+6)).toUTCString(); 只是我已经更正了@RichardN的代码,该代码有一个小错误
Azeez 2014年

59
“作为用户的锻炼”……真的吗?
adius

61

请小心接受的答案,因为它不会将时间设置为00:00:00和23:59:59,所以您可能会遇到问题。

我建议使用Moment.js处理日期。对于您的情况:

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

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

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


19
如果您使用矩,请使用“ isoweek”代替“ week”,否则它将从星期日开始,并以星期六结束,因此 var startOfWeek = moment().startOf('isoweek').toDate(); var endOfWeek = moment().endOf('isoweek').toDate();
Brugolo 2014年

谢谢大家节省了我的时间:-)
Syed Ehtsham Abbas 2015年

1
要在不使用moment.js的情况下计算时间,请使用Date.setHours:curr.setHours(0,0,0,0); lastday.setHours(23,59,59,59);
matadur

必须是“ isoWeek”而不是“ isoweek”
Mayur Saner

Love moment js,那里最好的日期/时间库之一!
维珀

49

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

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

希望它会有用。


2
是的,但是@totymedii,Raynos的答案在2019年3月1日是错误的,我有证据证明,第一天::周日,2019年2月24日,格林尼治标准时间最后一天::周六,2019年2月2日,08:33:48 GMT
Deepak Patel

14

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

1天= 86,400,000毫秒。

JS日期值以毫秒为单位

食谱:计算出需要删除多少天才能获得一周的开始日期(乘以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

3
这不起作用,因为使用DST,日子并不总是长86,400,000毫秒...
ValarDohaeris

9

出色的(且不可变的date-fns库最简洁地处理了此问题:

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

默认的一周的开始日期是星期日(0),但可以将其更改为星期一(1),如下所示:

const start = startOfWeek(date, {weekStartsOn: 1});
const end = endOfWeek(date, {weekStartsOn: 1});

1
加1用于使用date-
fns

@RobG您使用的任何方法都将具有默认的一周的第一天。
Freewalker

4

你可以做这样的事情

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

其中startDay是一个从0到6,其中0表示星期日(即1 =星期一,2 =星期二,等等)。


3

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

如果您将“日期设置”设置为2014年7月1日,则第一天显示为2014年6月29日,最后一天显示为2014年6月5日,而不是2014年7月5日

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

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

如果使用不正确,则在月初和月末使用setDate会导致错误的星期 ”。
RobG

3

这可以跨年和月更改。

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

现在,这似乎是多余的。smh
Chris Lang

以及从星期一开始的几周?
RobG

@RobG请参阅
湿婆

2

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

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

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

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

如果我们仅使用“ 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");

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


2
        //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()) ));
    }, 

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

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

在此处输入图片说明

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

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

这对于任何约会方案都是有用的。


1

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

有用


1

尽管这个问题似乎已经过时,但我必须指出一个问题。
问题: 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;

0

很好的建议,但您最后一天遇到了一个小问题。您应该将其更改为:

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

并非所有的时间都是24小时长,可以观察到夏时制。
RobG

0

瞬间方法在所有情况下都对我有效(尽管我尚未测试年终,,年等边界)。如果要从星期一开始,则上述代码中只有更正是参数“ isoWeek”。

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

0

仅使用纯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;
};

一周的最后一天距离一周的第一天仅6天

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

测试:

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

0

的JavaScript

function getWeekDays(curr, firstDay = 1 /* 0=Sun, 1=Mon, ... */) {
  var cd = curr.getDate() - curr.getDay();
  var from = new Date(curr.setDate(cd + firstDay));
  var to = new Date(curr.setDate(cd + 6 + firstDay));

  return {
    from,
    to,
  };
};

打字稿

export enum WEEK_DAYS {
  Sunday = 0,
  Monday = 1,
  Tuesday = 2,
  Wednesday = 3,
  Thursday = 4,
  Friday = 5,
  Saturday = 6,
}

export const getWeekDays = (
  curr: Date,
  firstDay: WEEK_DAYS = WEEK_DAYS.Monday
): { from: Date; to: Date } => {
  const cd = curr.getDate() - curr.getDay();
  const from = new Date(curr.setDate(cd + firstDay));
  const to = new Date(curr.setDate(cd + 6 + firstDay));

  return {
    from,
    to,
  };
};

0

我们添加了jquery代码,显示了从星期一到星期日的当前星期几。

var d = new Date();
var week = [];
var _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for (let i = 1; i <= 7; i++) {
    let first = d.getDate() - d.getDay() + i; 
    let dt = new Date(d.setDate(first));
    var _day = _days[dt.getDay()];
     var _month = _months[dt.getMonth()];
     var _date = dt.getDate();
     if(_date < 10 ){
         _date = '0' +_date;
     }
     var _year = dt.getFullYear();
     var fulldate = _day+' '+_month+' '+_date+' '+_year+' ';
     week.push(fulldate);
  }
console.log(week);

此代码将工作日存储在名为week的数组中。数组中存储的日期格式为Day Mon Date Year,表示先显示一周的第一天,然后显示月份,日期和年份。
Neeraj Singh

这个“ jQuery代码”如何?使用相同的技术,有许多更简单的答案。
RobG

0

一个有很多答案的老问题,所以另一个问题不会成为问题。一些通用功能可以获取各种时间单位的开始和结束时间。

对于startOfendOf week,一周的开始日期默认为星期日(0),但可以传递任何一天(星期一-1,星期二-2,等等)。虽然只使用公历。

该函数不会更改源日期,因此要查看日期是否与其他日期位于同一星期(从星期一开始的星期):

if (d >= startOf('week', d1, 1) && d <= endOf('week', d1, 1)) {
  // d is in same week as d1
}

或从星期日开始的当前一周:

if (d >= startOf('week') && d <= endOf('week')) {
  // d is in the current week
}

// Returns a new Date object set to start of given unit
// For start of week, accepts any day as start
function startOf(unit, date = new Date(), weekStartDay = 0) {
  // Copy original so don't modify it
  let d = new Date(date);
  let e = new Date(d);
  e.setHours(23,59,59,999);
  // Define methods
  let start = {
    second: d => d.setMilliseconds(0),
    minute: d => d.setSeconds(0,0),
    hour  : d => d.setMinutes(0,0,0),
    day   : d => d.setHours(0,0,0,0),
    week  : d => {
      start.day(d);
      d.setDate(d.getDate() - d.getDay() + weekStartDay);
      if (d > e) d.setDate(d.getDate() - 7);
    },
    month : d => {
      start.day(d);
      d.setDate(1);
    },
    year  : d => {
      start.day(d);
      d.setMonth(0, 1);
    },
    decade: d => {
      start.year(d);
      let year = d.getFullYear();
      d.setFullYear(year - year % 10);
    },
    century: d => {
      start.year(d);
      let year = d.getFullYear();
      d.setFullYear(year - year % 100);
    },
    millenium: d => {
      start.year(d);
      let year = d.getFullYear();
      d.setFullYear(year - year % 1000);
    }
  }
  start[unit](d);
  return d;
}

// Returns a new Date object set to end of given unit
// For end of week, accepts any day as start day
// Requires startOf
function endOf(unit, date = new Date(), weekStartDay = 0) {
  // Copy original so don't modify it
  let d = new Date(date);
  let e = new Date(date);
  e.setHours(23,59,59,999);
  // Define methods
  let end = {
    second: d => d.setMilliseconds(999),
    minute: d => d.setSeconds(59,999),
    hour  : d => d.setMinutes(59,59,999),
    day   : d => d.setHours(23,59,59,999),
    week  : w => {
      w = startOf('week', w, weekStartDay);
      w.setDate(w.getDate() + 6);
      end.day(w);
      d = w;
    },
    month : d => {
      d.setMonth(d.getMonth() + 1, 0);
      end.day(d);
    },  
    year  : d => {
      d.setMonth(11, 31);
      end.day(d);
    },
    decade: d => {
      end.year(d);
      let y = d.getFullYear();
      d.setFullYear(y - y % 10 + 9);
    },
    century: d => {
      end.year(d);
      let y = d.getFullYear();
      d.setFullYear(y - y % 100 + 99);
    },
    millenium: d => {
      end.year(d);
      let y = d.getFullYear();
      d.setFullYear(y - y % 1000 + 999);
    }
  }
  end[unit](d);
  return d;
}

// Examples
let d = new Date();

['second','minute','hour','day','week','month','year',
 'decade','century','millenium'].forEach(unit => {
   console.log(('Start of ' + unit).padEnd(18)  + ': ' +
   startOf(unit, d).toString());
   console.log(('End of ' + unit).padEnd(18)  + ': ' +
   endOf(unit, d).toString());
});


0

对@Chris Lang答案的零钱。如果您希望星期一作为第一天,请使用它。

Date.prototype.GetFirstDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay() +7)));
}

var today = new Date();

alert(today.GetFirstDayOfWeek());

alert(today.GetLastDayOfWeek());

Thaks @克里斯·朗(Chris Lang)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.