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

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-11 12:12:47

问题


For example, in the case of 03/27/2016 to 04/02/2016, the dates fall in different months.

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

回答1:


The getDay method returns the number of the day in the week, with Sunday as 0 and Saturday as 6. So if your week starts on Sunday, just subtract the current day number in days from the current date to get the start, and add 6 days get the end, e.g.

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



回答2:


I like the moment library for this kind of thing:

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



回答3:


You can try this:

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


来源:https://stackoverflow.com/questions/36292726/how-to-get-first-and-last-day-of-current-week-when-days-are-in-different-months

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!