简体   繁体   English

日期函数传递未定义的对象

[英]date function passing undefined object

在此输入图像描述

function addDays(date, days) {

          var result = new Date(date);
          console.log("initialdate"+result);
          result.setDate(result.getDate() + days);
          result=result.toLocaleDateString();
          result = result.split(' ')[0];
          return result;
     }

I am trying to add days to a date, however when I convert a date into object I get an error as Invalid date 我正在尝试将日期添加到日期,但是当我将日期转换为对象时,我会收到错误作为无效日期

This is the HTML code. 这是HTML代码。

<div class="form-line"> <label for="date">Date</label> <input type="text" class="form-control datepicker" id="edit_date" placeholder="Enter Date" required="true" value>

The problem that you are having is your input format. 您遇到的问题是您的输入格式。 For parsing to work the format will need to be either YYYY/MM/DD or MM/DD/YYYY . 要解析工作,格式必须是YYYY/MM/DDMM/DD/YYYY

 function addDays(date, days) { var result = new Date(date); console.log("initialdate: "+result); result.setDate(result.getDate() + days); result=result.toLocaleDateString(); result = result.split(' ')[0]; console.log("return: "+result); return result; } addDays("05/25/2019", 5); addDays("2019/05/24", 5); 

To achieve expected result, use below option of changing date in 'DD/MM/YYYY' to valid ISO 8601 format for Date constructor 要获得预期结果,请使用以下选项将“DD / MM / YYYY”中的日期更改为Date构造函数的有效ISO 8601格式

  1. format date to new Date(YYYY, MM, DD) by splitting date in format -DD/MM/YYYY 通过以-DD / MM / YYYY格式分割日期,将日期格式化为新日期(YYYY,MM,DD)
  2. Month value starts from 0 for Jan , decrease by 1 for getting valid month 月值从1开始为0,对于获得有效月份减少1
  3. Add days using setDate 使用setDate添加天数

 function addDays(date, days) { let fomarttedDate = date.split("/") var result = new Date(fomarttedDate[2], fomarttedDate[1] -1, fomarttedDate[0]); result.setDate(result.getDate() + days); result=result.toLocaleDateString(); result = result.split(' ')[0]; return result; } console.log(addDays("23/05/2019", 2)) 

Please refer this link for more details on datestring valid formats 有关datetring有效格式的更多详细信息,请参阅此链接
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

codepen for reference - https://codepen.io/nagasai/pen/zQvpaa codepen供参考 - https://codepen.io/nagasai/pen/zQvpaa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM