在文本字段中向日期添加月数

Add Number of months to a Date in a text field

本文关键字:添加 日期 文本 字段      更新时间:2023-09-26
function addDays(){ 
      var myDate =document.getElementById('treatdate'); 
      var numberOfDaysToAdd = document.getElementById('resultdays'); 
      var tset = numberOfDaysToAdd.value; 
      var result1 = myDate.value.addMonths(parseInt(tset)); 
      var pldate= moment(result1).format('YYYY-MM-DD');
      return pldate; }

'treatdate'是从数据库中提取的治疗日期的id。

您总是可以使用moment.js库进行日期操作。http://momentjs.com/

对于你的问题,你可以这样做。

function addDays(){
        var datefrmDb = $('#treatdate').val();
        var monthstoadd= $('#resultdays').val();
        var new_date = (moment(datefrmDb, "YYYY-MM-DD").add('months', monthstoadd)).format("YYYY-MM-DD");
        return new_date;
    }

如果您的日期格式是yyyy-MM-dd

var myDate = new Date(document.getElementById('treatdate').value); 

将显示日期和时间。
例子:

var dd = new Date("2014-02-02 11:11:11")

控制台日志

Sun Feb 02 2014 11:11:11 GMT+0000 (GMT Standard Time)

看看这段代码是否能帮助您理解如何操作日期。要更改/添加日期到Date()对象,可以使用setMonth()方法。

numberOfMonthsToAdd = 5; // the number of months that you want to add
date = new Date(); // creating a Date object
date.setMonth(numberOfMonthsToAdd); // adding the number of months

请注意,您可以添加超过12的数字-该对象处理日期,并跳转到下一年。