我试着通过像表格一样点击日历来给某些日子添加天数。
首先,我可以通过点击获得endday,然后,我想在上面添加120天。
<td id="207" data-class-index="0" data-day="2018/5/21">21</td>
我的代码如下所示
endday=new Date($(this).data('day'))
console.log("enddate",endday);
upperlimit=endday.setDate(endday.getDate()+120);
console.log("upperlimit",upperlimit);
当我尝试添加天数时,似乎返回当前时间。像这样
enddate Thu Sep 13 2018 00:00:00 GMT+0900 (Japan Standard Time)
upperlimit Fri Dec 20 2019 11:49:34 GMT+0900 (Japan Standard Time)
我想知道为什么会发生这个问题,如果有人有这样的经验,请让我知道如何解决。
谢谢
发布于 2019-12-20 03:54:22
正如@Barmar所述,upperlimit
在Unix time中返回日期。将该调用包装在new Date(...)
中应该可以解决它。
$("#btn").on('click', () => {
let endday = new Date($("#207").data("day"));
let upperlimit = new Date(endday.setDate(endday.getDate()+120));
// Have to add +1 to .getMonth() because JS handles months as 0-11 not 1-12
let resultHtml = `${upperlimit.getFullYear()}/${upperlimit.getMonth() + 1}/${upperlimit.getDate()}`
$("#result").html(resultHtml);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="207" data-class-index="0" data-day="2018/5/21">2018/5/21</p>
<button id="btn">Click to add 120 days</button>
<p id="result"></p>
发布于 2019-12-20 03:19:00
您似乎通过在endday
上调用setDate
来更改它的日期。相反,您应该首先将upperlimit
声明为新日期,然后直接设置它。
const endDay = new Date('Thu Sep 13 2018 00:00:00 GMT+0900');
console.log("endDay", endDay);
var upperLimit = new Date(endDay);
upperLimit.setDate(endDay.getDate() + 120);
console.log("upperLimit", upperLimit);
发布于 2019-12-20 03:28:41
尝试下面的方法
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
console.log(date.addDays(2));
https://stackoverflow.com/questions/59419322
复制相似问题