JSFiddle - React, Tailwind, and code Playground

by Luke Marlow

HTML

<b></b><br>
<input type="text" id="start_date" value="25/01/2017"><br>
<br>
<input type="text" id="months" value="12"><br>
<br>
<div id="date">Click below to generate</div>
<br>
<button onClick="generate_date()">Calculate</button>

JavaScript

generate_date = function()
{
		console.log('Moon.');

		var start  = document.getElementById('start_date').value;
    var months = document.getElementById('months').value;
    var end    = add_months_to_uk_date(start, months);

		document.getElementById('date').innerHTML = end;
}

add_months_to_uk_date = function(start_date, months_to_add)
{
		/* STRING FUNCTIONS */
    // This allows us to use pLeft(2, 0) on the date fields, for example
    String.prototype.padLeft = function (length, character) { 
        return new Array(length - this.length + 1).join(character || ' ') + this; 
    };

		/** DATE FUNCTIONS */
		Date.isLeapYear = function (year) { 
        return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); 
    };

    Date.getDaysInMonth = function (year, month) {
        return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
    };

    Date.prototype.isLeapYear = function () { 
        return Date.isLeapYear(this.getFullYear()); 
    };

    Date.prototype.getDaysInMonth = function () { 
        return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
    };

    Date.prototype.addMonths = function (value) {
        var n = this.getDate();
        this.setDate(1);
        this.setMonth(this.getMonth() + value);
        this.setDate(Math.min(n, this.getDaysInMonth()));
        return this;
    };

		/** CODE TO PROCESS REQUEST */
		var months = parseInt(months_to_add);
    if (months <= 0) { 
    		return start_date;
    } else {
    		var s = start_date.split('/');
        var y = parseInt(s[2]);
        var m = parseInt(s[1]);
        var d = parseInt(s[0]);

				var sObj = new Date(y, (m - 1), d);
        var eObj = sObj.addMonths(months);
        var fObj = new Date(eObj);

				return [
	        	String(fObj.getDate()),
  	        String(fObj.getMonth() + 1).padLeft(2, '0'),
    	      String(fObj.getFullYear()).padLeft(4, '20')
        ].join('/');
		}
}