javascript 当日期在不同月份时,如何获得当前周的第一天和最后一天?

ryhaxcpt  于 2023-02-28  发布在  Java
关注(0)|答案(4)|浏览(146)

例如,在2016年3月27日至2016年4月2日的情况下,日期位于不同月份。

var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
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();
3qpi33ja

3qpi33ja1#

  • getDay* 方法返回一周中的天数,其中星期日为0,星期六为6。因此,如果一周从星期日开始,只需从当前日期减去当前天数即可得到开始日期,加上6天即可得到结束日期,例如:
function getStartOfWeek(date) {
  
  // Copy date if provided, or use current date if not
  date = date? new Date(+date) : new Date();
  date.setHours(0,0,0,0);
  
  // Set date to previous Sunday
  date.setDate(date.getDate() - date.getDay());
  
  return date;
}

function getEndOfWeek(date) {
  date = getStartOfWeek(date);
  date.setDate(date.getDate() + 6);
  return date; 
}
  
document.write(getStartOfWeek());

document.write('<br>' + getEndOfWeek())

document.write('<br>' + getStartOfWeek(new Date(2016,2,27)))

document.write('<br>' + getEndOfWeek(new Date(2016,2,27)))
kpbpu008

kpbpu0082#

您可以找到以下问题的解决方案。

let currentDate = new Date; // get current date
let first = currentDate.getDate() - currentDate.getDay();
var last = first + 6; // last day is the first day + 6
let firstDayWeek = new Date(currentDate.setDate(first)).toISOString();
var lastDayWeek = new Date(currentDate.setDate(last)).toISOString();
console.log(firstDayWeek, "first Day in week")
console.log(lastDayWeek, "end Day in week")
1dkrff03

1dkrff033#

我喜欢moment library来处理这类事情:

moment().startOf("week").toDate();
moment().endOf("week").toDate();
bjp0bcyl

bjp0bcyl4#

你可以试试这个:

var currDate = new Date();
day = currDate.getDay();
first_day = new Date(currDate.getTime() - 60*60*24* day*1000); 
last_day = new Date(currDate.getTime() + 60 * 60 *24 * 6 * 1000);

相关问题