[Demo] Add Years and Months to a Date in JavaScript

[Demo] Add Years and Months to a Date in JavaScript. For example, want to add 2.5 years or 1.5 years to current date in JavaScript

by Rahul Saraswat

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<div>Date:<input id="txtDt" type="text" /></div>
<br/>
<input type="button" onclick="calculatedDate()" value="Add 2.5 years" /><br/>
<p id="paraDate"></p>

JavaScript

$(document).ready(function () {
    $('#txtDt').datepicker();
});

function calculatedDate(){
    var currentDate = new Date();
    //Adding 2 years
    var DateAfterAdded2years = new Date(currentDate.getFullYear() + 2, currentDate.getMonth(), currentDate.getDate());	
    //Adding 6 moths more
    var FinalDate = new Date(DateAfterAdded2years.getFullYear(), DateAfterAdded2years.getMonth() + 6, DateAfterAdded2years.getDate());
    document.getElementById('paraDate').innerHTML =moment(FinalDate).format('DD/MM/YYYY');
    
    

}