JSFiddle - React, Tailwind, and code Playground

by jasenhk

HTML

<ul>
    <li>Amt:
        <input type="text" id="amount" value="500000" />
    </li>
    <li>ThruDate:
        <input type="text" id="thruDate" class="dtp" />
    </li>
    <li>ClosingDate:
        <input type="text" id="closingDate" class="dtp" />
    </li>
    <li>PeriodMonths:
        <input type="text" id="periodMonths" value="12" />
    </li>
</ul>
<button>Compute</button>
<input type="text" id="result" />
<div>
    <label>Days: <input type="text" id="days" readonly /></label>
</div>

JavaScript

$(".dtp").datepicker();

$("button").on("click", function (e) {
    var amount = $("#amount").val();
    var thruDate = new Date($("#thruDate").val());
    var closingDate = new Date($("#closingDate").val());
    var periodMonths = $("#periodMonths").val();

    var result = prorate(amount, thruDate, closingDate, periodMonths);
    $("#result").val(result);
});
Date.prototype.addMonths = function (months) {
    var tmp = new Date(this)
    var thisDoM = tmp.getDate()
    tmp.setDate(thisDoM + 1)
    var nextDoM = tmp.getDate()
    tmp = new Date(this)
    var lastDate = false
    if (nextDoM < thisDoM) {
        tmp.setDate(1)
        months += 1
        lastDate = true
    }
    tmp.setMonth(this.getMonth() + months)
    var years = tmp.getYear() - this.getYear()
    var actualMonths = years * 12 + tmp.getMonth() - this.getMonth()
    if (actualMonths > months) lastDate = true
    if (lastDate) tmp.setDate(0)
    return (new Date(tmp))
};

function prorate(amount, thruDate, closingDate, periodMonths) {
    var periodDays;
    var thruTime = thruDate.getTime() - thruDate.getTimezoneOffset() * 60000;
    var closingTime = closingDate.getTime() - closingDate.getTimezoneOffset() * 60000;
    if (closingTime < thruTime) {
        var prevThru = thruDate.addMonths(-periodMonths);
        var prevTime = prevThru.getTime() - prevThru.getTimezoneOffset() * 60000;
        periodDays = (thruTime - prevTime) / 86400000; // ms in a day
        console.log("<", periodDays);
    } else {
        var nextThru = thruDate.addMonths(periodMonths);
        var nextTime = nextThru.getTime() - nextThru.getTimezoneOffset() * 60000;
        console.log(nextThru);
        while (closingTime > nextTime) {
            nextThru = nextThru.addMonths(periodMonths);
            nextTime = nextThru.getTime() - nextThru.getTimezoneOffset() * 60000;
        }
        periodDays = (nextTime - thruTime) / 86400000;
        console.log(">", periodDays);
    }
    var days = (thruTime - closingTime)...