![](/img/trans.png)
[英]Get start date and end date of current week (week start from monday and end with sunday )
[英]Get start and end of week with the start on Monday and end on Sunday in Javascript
function getStartAndEndOfWeek(date) {
var curr = date ? new Date(date) : new Date();
var first = curr.getDate() - curr.getDay();
var firstday = new Date(curr.setDate(first));
var lastday = new Date(curr.setDate(firstday.getDate() + 6));
return [firstday, lastday];
}
我無法將一周的開始設置為星期一。 上面的代碼將第一天作為星期日。 此外,如果我們添加 first plus one,它將以星期一為開始,但問題在於讓我們說(06/29/2014,星期日)是輸入,它應該返回(06/23/2014 作為開始和 06 /29/2014) 作為結尾。 我們怎樣才能做到這一點? 如果我添加“first + 1”,它將返回 06/30/2014 作為開始日期和 07/06/2014 作為結束日期。 有什么幫助嗎? 謝謝。
回答:
function getStartAndEndOfWeek(date) {
//Calculating the starting point
var curr = date ? new Date(date) : new Date();
var first = curr.getDate() - dayOfWeek(curr);
var firstday, lastday;
if (first < 1) {
//Get prev month and year
var k = new Date(curr.valueOf());
k.setDate(1);
k.setMonth(k.getMonth() - 1);
var prevMonthDays = new Date(k.getFullYear(), (k.getMonth() + 1), 0).getDate();
first = prevMonthDays - (dayOfWeek(curr) - curr.getDate());
firstday = new Date(k.setDate(first));
lastday = new Date(k.setDate(first + 6));
} else {
// First day is the day of the month - the day of the week
firstday = new Date(curr.setDate(first));
lastday = new Date(curr.setDate(first + 6));
}
return [firstday, lastday];
}
function dayOfWeek(date, firstDay) {
var daysOfWeek = {
sunday: 0,
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
};
firstDay = firstDay || "monday";
var day = date.getDay() - daysOfWeek[firstDay];
return (day < 0 ? day + 7 : day);
}
如何制作一種簡單的方法來讓您輕松地控制一周的第一天:
(function() {
var original = Date.prototype.getDay;
var daysOfWeek = {
sunday: 0,
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
};
Date.prototype.getDay = function(weekBegins) {
weekBegins = (weekBegins || "sunday").toLowerCase();
return (original.apply(this) + 7 - daysOfWeek[weekBegins]) % 7;
};
})();
然后,您可以簡單地使用:
var first = curr.getDate() - curr.getDay("monday"),
last = first + 6;
您可以通過移動getDay()的結果,然后將結果取模,首先將其設置為星期一。
var first = curr.getDate() - ((curr.getDay() + 6) % 7);
簡單多了
var numberdayweek = [6,0,1,2,3,4,5]; fecha = new Date(); console.log(numberdayweek[fecha.getDay()]);
找到其他解決方案:
const getDayIndexMondaySunday = (date) =>date.getDay() === 0 ? 6 : date.getDay() - 1 // Result on Today console.log(getDayIndexMondaySunday(new Date()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.