保存购买日期并为其添加X时间

时间:2017-10-20 19:45:30

标签: javascript node.js date

我正在创建一个节点应用,用户可以使用以下HTML输入选择bought日期<{1}}

然后使用<input placeholder="Date Bought" class="textbox-n form-control" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="bought" name="bought">将其存储到mongodb中,并且用户将一些月份输入到具有var bought = req.body.bought;的另一个HTML输入中,我需要使用name="warranty"日期转换为日期然后bought个月。我该如何添加这些?我试过这个:

warranty

根据guide

2 个答案:

答案 0 :(得分:1)

尝试使用Moment.js

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

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

Moment只是JS日期对象的包装器,因此它无缝且易于使用。您可以将其安装为npm包,将其导入您的页面,并将其传递给不同格式的日期字符串(请参阅文档)或任何有效的javascript日期对象。我暂时不能处理日期,因为它应该是标准库的一部分。

答案 1 :(得分:0)

浏览代码和注释,了解代码无法正常运行的原因

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" />

您还需要为代码添加一些错误处理。