Javascript Data Type How to - Compare dates in different formats








Question

We would like to know how to compare dates in different formats.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!-- w w w  .j a  v a 2  s.co m-->
function compareDates(milliSeconds, dateString) {
    var year,
        month,
        day,
        tempDate1,
        tempDate2,
        parts;
    tempDate1 = new Date(milliSeconds);
    year = tempDate1.getFullYear();
    month =  tempDate1.getDate();
    day = tempDate1.getDay();
    tempDate1 = new Date(year, month, day).getTime();
    parts = dateString.split("/");
    tempDate2 = new Date(parts[0], parts[1] - 1, parts[2]).getTime();
    if (tempDate1 === tempDate2) {
        return 0;
    }
    if (tempDate1 < tempDate2) {
        return -1;
    }
    return 1;
}
var format1 = 1381308375118,
    format2 = "2013/08/26";
document.writeln(compareDates(format1, format2));
}
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: