how do I Compare 2 dates in html5?

anthony levano picture anthony levano · Jan 12, 2016 · Viewed 12.4k times · Source

This is my code.

<input type="date" name="startDate" id="startDate" />
<input type="date" name="endDate" id="endDate" />

I want startdate does not exceed endDate, is there a way to compare dates without using jquery ? like in asp CompareValidator

Answer

Let&#39;sRefactor picture Let'sRefactor · Jan 12, 2016

You can do it,

<input type="date" name="endDate" id="endDate" onblur="compare();"/>

and your script,

function compare()
{
    var startDt = document.getElementById("startDate").value;
    var endDt = document.getElementById("endDate").value;

    if( (new Date(startDt).getTime() < new Date(endDt).getTime()))
    {
        // Your code here
    }
}

do necessory null validations as well.