0

我正在尝试使用我拥有的 2 个日期创建一个新日期。基本上是我的新约会

Output:

 Date 1 = (presentdate +1 month , endDate+1 day, presentdate+1 year);


            //Example 1: 
            var presentDate = "11/12/2018";
            var endDate = "2/8/2018";
            var Dat1 = "12/9/2018"; //new date

           //Example 2 :
            var presentDate = "11/12/2018";
            var endDate = "5/25/2018";
            var Dat1 = "12/26/2018"; //new date

          //Example 3 :
            var presentDate = "1/5/2018";
            var endDate = "5/30/2018";
            var Date1 = "2/31/2018"; // invalid date
            //should've been 2/28/2018 since that is the last day of the month

         //Example 4:
            var presentDate = "3/5/2018";
            var endDate = "10/30/2018";
            var Date1 = "4/31/2018"; //Invalid date. Should've been 4/30/2019 since it's last day of the month

我的代码:

            var mPresent = moment(presentDt);
            var mEnd = moment(eDt);

            var Date1 = moment({
            year: mPresent.year(), // get presentDt's year
            month: mPresent.add(1, 'month').month(), // get presentDt's month
            date: mStart.date() // get startdt day of the month
        });

console.log(Date1);

它不适用于所有情况,因为并非每个月都有 30,31 天,然后是闰年。我需要创建一个有效的日期,因为在某些情况下它返回无效日期。

任何帮助表示赞赏。谢谢!

4

1 回答 1

0

我不完全确定你的代码发生了什么,但我砍掉了大部分代码,基本上做了一个 1-liner 来计算月数差异 - 似乎有效。

document.querySelector("#ok").addEventListener("click", function () {
  var paymentDate = document.getElementById("presentDate").value;
  var etDate = document.getElementById("endDate").value;

  var RemainingPayments = moment(etDate).diff(moment(paymentDate), 'months');
  console.log(RemainingPayments);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<label>Present date</label><input id="presentDate" name="presentDate"  type="date">
<label>End Date</label> <input id="endDate" name="endDate" type="date">
<button id='ok'>OK</button>

于 2018-12-06T21:32:43.357 回答