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

How to get first and last day of current week when days are in different months?

例如,在 03/27/2016 到 04/02/2016 的情况下,日期属于不同的月份。

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

我喜欢moment library这种东西:

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

你可以试试这个:

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

getDay 方法 returns 一周中的第几天,周日为 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)))