我需要计算最近一个周末之前的最后一个星期一的日期。使用了我认为是最常见的堆栈溢出建议之后,我得到了以下代码:
const getDayOfTheWeek = () => {
let date = new Date();
let clonedDate = new Date(date.getTime());
console.log(clonedDate);
const dow = clonedDate.getDay();
console.log(dow);
const offset = dow+6;
console.log(offset);
const newDate = new Date(clonedDate.setDate(clonedDate.getDate() - offset));
console.log(newDate);
const newNewDate = new Date(newDate.getTime());
console.log(newNewDate);
const day = newNewDate.getDate();
const month = newNewDate.getMonth();
const year = newNewDate.getYear();
console.log('the year is ',year, 'the month is ', month);
}
getDayOfTheWeek();
它将返回年份118和月份5,这不是我需要的星期一。另一方面,newNewDate是最后一个星期一。我想知道是什么原因造成的。我知道有太多不需要的重新分配。请帮忙。
答案 0 :(得分:2)
无论您做什么都是完美的,唯一的错误是您正在使用 getMonth()和 getYear()并误解了它们。
date.getMonth()给您的月份范围是0到11。所以5实际上是六月月。
date.getYear()该方法返回年份减去1900,因此实际值为118 + 1900 = 2018,相反,您可以使用 date.getFullYear()返回2018
此外,您不需要太多步骤。
可以使用newDate停止功能,如下所示:
const getDayOfTheWeek = () => {
let date = new Date();
let clonedDate = new Date(date.getTime());
console.log(clonedDate);
const dow = clonedDate.getDay();
console.log(dow);
const offset = dow+6;
console.log(offset);
const newDate = new Date(clonedDate.setDate(clonedDate.getDate() - offset));
console.log(newDate);
const day = newDate.getDate();
const month = newDate.getMonth() + 1;
const year = newDate.getFullYear();
console.log('the year is ',year, 'the month is ', month);
}
getDayOfTheWeek();
这将给出“年份是2018,月份是6”
希望这会有所帮助。