简体   繁体   中英

String date to System date compare

I have two dates , first date is string coming from input text like 01-01-2011(dd-MM-yyyy) and second date is current date or system date(new Date()).

I have to compare the input date to current date(gretter or equal). I'm facing issue of NaN and did not find efficient help in google.

Any help will be appreciate.

Please try with the below code snippet.

var from = "13-05-2014".split("-");
var dt1 = new Date(from[2], from[1] - 1, from[0]);
var dt2 = new Date();
if (dt1 - dt2 > 0) {
    alert("current or future date");
}

If you want difference in detail format then please check this link.

var date=new Date();
var today= date.getDate()+"-"+(date.getMonth()-1)+"-"+date.getFullYear();

and compare with this date

or make two dates and use this method

function datediff(date1, date2) {
    var y1 = date1.getFullYear();
    var m1 = date1.getMonth();
    var d1 = date1.getDate();
    var y2 = date2.getFullYear();
    var m2 = date2.getMonth();
    var d2 = date2.getDate();
    if (d1 < d2) {
        m1--;
        var date=new Date(y2, m2, 1, 12);
        date.setDate(0);
        d1 += date.getDate();
    }
    if (m1 < m2) {
        y1--;
        m1 += 12;
    }
    return [y1 - y2, m1 - m2, d1 - d2];
}

if it returned [0,0,0] two dates are equal

<!DOCTYPE html>
<html>
<head>
<script>

Date.prototype.format=function(){
    var year=this.getFullYear();
    var month=this.getMonth();
    var date=this.getDate();
    return year+"-"+month+"-"+date;
}

var usrdate=new Date();
usrdate.setFullYear(2014,4,13);
usrdate=usrdate.format();

function compare(usrdate)
{
    var sysdate=new Date().format();
    if(sysdate>usrdate)
       alert("System Date is greater");
    else if(sysdate<usrdate)
       alert("User Date is greater");
    else
       alert("Both date is equal");
}

</script>
</head>
<body>
<p onclick="compare(usrdate);">Compare Date </p> 
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM