Skip to content
Advertisement

How Can I Calculate No Of Days From Two Dates

I want to Calculate no of days from two dates My date Format is dd-mmm-yyyy Like "10-Nov-2020" Can any one help me on same?

<script>
        var deFromDate;
        var deToDate;
        var statarr;
        function deFromDateChanged(s, e) {
            deFromDate = (s.GetInputElement().value)
            //statarr = deFromDate.split('-');
        }
        function deToDateChanged(s, e) {
            deToDate = (s.GetInputElement().value)
            var Difference_In_Time = deToDate.getTime() - deFromDate.getTime();
            var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
            alert(Difference_In_Days);
        }

    </script>

I am getting Error on getTime() Is there any other Approach to do same

Advertisement

Answer

Using Date.parse() (though it is discouraged due to inconsistent implementation)

function datediff(first, second) {
    return Math.round((second-first)/(1000*60*60*24));
}

const deFromDate = Date.parse('10-Nov-2020');
const deToDate = Date.parse('15-Nov-2020');

console.log(datediff(deFromDate, deToDate));

Manual parsing

var months = {
    'Jan' : 1,
    'Feb' : 2,
    'Mar' : 3,
    'Apr' : 4,
    'May' : 5,
    'Jun' : 6,
    'Jul' : 7,
    'Aug' : 8,
    'Sep' : 9,
    'Oct' : 10,
    'Nov' : 11,
    'Dec' : 12
}
function parseDate(str) {
    var [dd, mmm, yyyy] = str.split('-');
    return new Date(yyyy, months[mmm]-1, dd); // months are 0 indexed
}

function datediff(first, second) {
    return Math.round((second-first)/(1000*60*60*24));
}

const deFromDate = parseDate('10-Nov-2020');
const deToDate = parseDate('15-Nov-2020');

console.log(datediff(deFromDate, deToDate));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement