如何在JavaScript中获得下周一?我无法在互联网上找到任何相关内容,我也尝试了很多代码并对此有所了解,但我无法做到。
这是我的代码:
var d = new Date();
var day = d.getDay();
d = new Date(d.setDate(d.getDate() + day + (day == 0 ? -6 : 2)));
答案 0 :(得分:32)
这样做:
var d = new Date();
d.setDate(d.getDate() + (1 + 7 - d.getDay()) % 7);
console.log(d);
答案 1 :(得分:12)
如果今天是星期一,这将在下周一给出
var d = new Date();
d.setDate(d.getDate() + (7-d.getDay())%7+1);
如果今天是星期一,这将导致今天
var d = new Date();
d.setDate(d.getDate() + ((7-d.getDay())%7+1) % 7);
答案 2 :(得分:2)
var closestMonday = () => {
var curr_date = new Date(); // current date
var day_info = 8.64e+7; // milliseconds per day
var days_to_monday = 8 - curr_date.getDay(); // days left to closest Monday
var monday_in_sec = curr_date.getTime() + days_to_monday * day_info; // aleary Monday in seconds from 1970
var next_monday = new Date(monday_in_sec); // Monday in date object
next_monday.setHours(0,0,0);
return next_monday;
}
答案 3 :(得分:2)
其他回复似乎没有考虑到“下周一”应该是一天的开始。以下是我最近的实施方式:
function getNextMonday() {
const now = new Date()
const today = new Date(now)
today.setMilliseconds(0)
today.setSeconds(0)
today.setMinutes(0)
today.setHours(0)
const nextMonday = new Date(today)
do {
nextMonday.setDate(nextMonday.getDate() + 1) // Adding 1 day
} while (nextMonday.getDay() !== 1)
return nextMonday
}
答案 4 :(得分:1)
使用moment.js,
moment().add(7, 'days').calendar();
答案 5 :(得分:1)
如果您需要处理时区,一个选项是使用UTCDate方法 setUTCDate()和 getUTCDate()。这样可以保持一致性,因此无论时区设置如何,计算都是相同的。
var d = new Date();
d.setUTCDate(d.getUTCDate() + (7 - d.getUTCDay()) % 7 + 1);
(这是上面的例子,在周一返回下一个星期一)
答案 6 :(得分:0)
请试试这个,
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1);
alert(new Date(d.setDate(diff)));
由于 阿米特
答案 7 :(得分:0)
如果您想要的一周中的实际日期是可变的(星期日,星期四,...),并且您想选择今天是否可以匹配,并且可能要从另一个日期开始(而不是今天),那么此功能可能会有用:
function getNextDayOfTheWeek(dayName, excludeToday = true, refDate = new Date()) {
const dayOfWeek = ["sun","mon","tue","wed","thu","fri","sat"]
.indexOf(dayName.slice(0,3).toLowerCase());
if (dayOfWeek < 0) return;
refDate.setHours(0,0,0,0);
refDate.setDate(refDate.getDate() + !!excludeToday +
(dayOfWeek + 7 - refDate.getDay() - !!excludeToday) % 7);
return refDate;
}
console.log("Next is: " + getNextDayOfTheWeek("Wednesday", false));
答案 8 :(得分:0)
这是我的解决方法
var days =[1,7,6,5,4,3,2];
var d = new Date();
d.setDate(d.getDate()+days[d.getDay()]);
console.log(d);
答案 9 :(得分:0)
或更简单:
let now = new Date();
let day = 1; // Monday
if (day > 6 || day < 0)
day = 0;
while (now.getDay() != day) {
now.setDate(now.getDate() + 1);
}
now.setDate(now.getDate() + 1);
console.log(now); // next Monday occurrence
答案 10 :(得分:0)
另一种方法是找到您想要的日期的偏移量(以天数计),将其转换为毫秒,并将其添加到您的开始日期:
select concat(fName,' ',
case length(mName)
when 0 then ''
else concat(mName, ' ') end, lName) as fullName