保存购买date并添加X时间到它

我正在创build一个节点应用程序,用户可以使用以下HTMLinputselectboughtdate: <input placeholder="Date Bought" class="textbox-n form-control" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="bought" name="bought">

然后使用var bought = req.body.bought;存储到一个mongodb var bought = req.body.bought; 和用户input一个月数到另一个HTML name="warranty" HTMLinput,我需要转换为使用boughtdate,然后warranty月份的date。 我如何添加这些? 我试过这个:

  var bought = req.body.bought; var warrantyMonths = req.body.warranty; var warranty = bought.setMonth(bought.getMonth()+ warrantyMonths); 

根据本指南

尝试使用Moment.js

如果保修月份是一个整数,您可以:

 var bought = moment(req.body.bought); var warrantyMonths = req.body.warranty; var warranty = moment(bought).add(warrantyMonths, "month"); 

Moment只是JSdate对象的包装,所以它是无缝和易于使用的。 您可以将它安装为npm包,将其导入到您的页面,并传递不同格式的datestring(请参阅文档)或任何有效的javascriptdate对象。 我不能用没有时间的日子工作了,它应该是标准库的一部分。

仔细阅读代码和注释,了解代码无法正常工作的原因

 function calculateWarranty() { // get the date text and convert into date Object var bought = new Date(document.getElementById('bought').value); // get the number of warranty months and convert to integer (second arguments ensures that the integer is base 10) // if you do not convert the number, it will do String concatenation while calling dateObj.setMonth(getMonth_int + warrant_string ) // for example: 2017-10-21 will give bought.getMonth() === 9 + "1", which will equal 91 instead of 10 var warrantyMonths = parseInt(document.getElementById('warranty').value, 10); // display in console for debugging console.log(bought); console.log(warrantyMonths); var boughtMonth = bought.getMonth(); // add bought month and warranty month (both should be integer as stated earlier) var warrantyMonth = boughtMonth + warrantyMonths; // set the month to bought object bought.setMonth(warrantyMonth); // result console.log(bought); } // adding event listeners on the input boxes document.querySelector('#bought').addEventListener('change', calculateWarranty); document.querySelector('#warranty').addEventListener('change', calculateWarranty); 
 <input id="bought" name="bought" class="textbox-n form-control" type="text" placeholder="Date Bought" onfocus="(this.type='date')" onblur="(this.type='text')" /> <input id="warranty" name="warranty" class="textbox-n form-control" type="number" value="1" />