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

时间:2011-03-06 12:10:42

标签: javascript date

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

25 个答案:

答案 0 :(得分:154)

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"

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

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

答案 1 :(得分:47)

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

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

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

这只是一个小用例,执行大量复杂操作非常简单。

您可以在此处了解详情:http://momentjs.com/

答案 2 :(得分:35)

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

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

希望它有用..

答案 3 :(得分:15)

这是开始第一天和最后一天的快捷方式。 知道:

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

答案 4 :(得分:8)

优秀(和不可变)date-fns library处理最简洁:

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

答案 5 :(得分:3)

你可以做这样的事情

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 =星期二等)。

答案 6 :(得分: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

答案 7 :(得分: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());

答案 8 :(得分:3)

我建议在这种情况下使用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");

周从星期日开始到星期六结束,如果我们只是使用'周'作为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");

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

答案 9 :(得分:2)

for i, (name, group) in enumerate(df.groupby('interval')):
    group.plot(kind="scatter", x='location', y='y_axis', 
               ax=axes[i], title="Interval {}".format(name))

这对任何日期场景都很有用。

答案 10 :(得分:2)

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

它有效

答案 11 :(得分: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;

答案 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()) ));
    }, 

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

它也适用于不同的月份和年份。 使用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);
    });

答案 13 :(得分:1)

很好的建议,但你在上个天遇到了一个小问题。 你应该把它改成:

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

答案 14 :(得分:0)

对于所有案例来说,当下的方法对我有效(尽管我没有测试像年末,闰年这样的界限)。如果你想从星期一开始这一周,只有上面代码中的更正是参数是“isoWeek”。

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

答案 15 :(得分:0)

只需使用纯JavaScript,您就可以使用下面的功能获取一周的第一天和最后一天,并自由设置一周开始的一周。

List<BsonDocument>

一周的最后一天是一周的第一天后的第6天

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

测试:

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

答案 16 :(得分: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,
  };
};

TypeScript

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

答案 17 :(得分: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);

答案 18 :(得分:0)

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

对于 startOf endOf 星期,星期的开始日期默认为星期日(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());
});

答案 19 :(得分: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

答案 20 :(得分:0)

function getMonday(d) {
    d = new Date(d);
    var day = d.getDay(),
        diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
    return new Date(d.setDate(diff));
  }
  
 console.log( getMonday(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())) )  // Mon Nov 08 2010

答案 21 :(得分:0)

var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 7)).toUTCString();
console.log(firstday, lastday)

I'm using the following code in but because of .toUTCString() i'm receiving the following error as show in image.

if i remove .toUTCString(). output which i receive is not as expected

答案 22 :(得分:0)

@SHIVA 的答案的小改动,即@Chris Lang 的答案已更改。 星期一第一次使用,当 today 是星期日时修复。

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() == 0 ? 7 : this.getDay()) + 7));
}

var today = new Date();

alert(today.GetFirstDayOfWeek());

alert(today.GetLastDayOfWeek());

答案 23 :(得分:0)

你也可以试试下面的

let weekBgnDt = new Date();
let weekEndDt = new Date();
let wBeginDateLng, wEndDateLng, diffDays,dateCols=[];

if (weekBgnDt.getDay() > 0) {
    diffDays = 0 - weekBgnDt.getDay();
    weekBgnDt.setDate(weekBgnDt.getDate() + diffDays)
}
weekEndDt = weekEndDt.setDate(weekBgnDt.getDate() + 6)

wBeginDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric', 
month: '2-digit' }).format(weekBgnDt);
wEndDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric', month: 
'2-digit' }).format(weekEndDt);

wBeginDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric', 
month: 'long' }).format(weekBgnDt);
wEndDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric', 
month: 'long' }).format(weekEndDt);

console.log(wBeginDate, "-", wBeginDateLng)
console.log(wEndDate, "-", wEndDateLng)

for(let i=weekBgnDt;i<=weekEndDt;){
  dateCols.push(new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric', 
  month: '2-digit' }).format(i));
  i=weekBgnDt.setDate(weekBgnDt.getDate()+1)
}


console.log({wBeginDate,wBeginDateLng,wEndDate,wEndDateLng,dateCols})

结果将打印为

{ wBeginDate: "16/05/2021", wBeginDateLng: "16 May 2021", wEndDate: "22/05/2021", wEndDateLng: "22 May 2021", dateCols: Array ["16/05/2021" ", "17/05/2021", "18/05/2021", "19/05/2021", "20/05/2021", "21/05/2021", "22/05/2021"] }

答案 24 :(得分:0)

纯香草JS。没有第三方库。

object StringTransformation extends App {
  
   val str = "aaabbcda"
   strTransform(str)
  
   def strTransform(str:String) {
     var count = 1
     for (i <- 1 until str.length) {
        if(str.charAt(i-1) == str.charAt(i)){
            count += 1
        }else{
            print(count+String.valueOf(str.charAt(i-1)))      
            count=1
        }
     }
     print(count+str.takeRight(1))
   }
}

^ 这将返回星期日早上 00 点到星期日早上 00 点。调整“7”以获得您想要的。