Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare dates in javascript with two different format?

function mainFunc() {
    dueDate = "30/12/2014";
    var firstReminderDate = dueDate;
    var today = new Date();
    var firstDate = convertToDate(firstReminderDate);
    if (today > firstDate) {
        //send reminder to A
    } else {
        // send reminder to B
    }
}

function convertToDate(dateString) {
    var dateData = dateString.split("/");
    var date = new Date(new Date().setFullYear(dateData[0], dateData[1] - 1, dateData[2]));
    return new Date(date);
}

I need to compare two dates not the time, and how to remove the time part and just compare the dates? The convertToDate() is returning the "Thu Jan 01 05:30:00 GMT+05:30 1970" everytime?

like image 778
Mr AJ Avatar asked May 08 '26 21:05

Mr AJ


1 Answers

You can simplify your code. To get a date from dd/mm/yyyy, simply splitting on /, reversing the result and joining it on '/' gives you yyyy/mm/dd, which is valid input for a new Date to compare to some other Date. See snippet

var report = document.querySelector('#result');
report.innerHTML += '30/12/2014 => '+ mainFunc('30/12/2014');
report.innerHTML += '<br>01/12/2014 => '+ mainFunc('01/01/2014');

function mainFunc(due) {
    due = due ? convertToDate(due) : new Date;
    return new Date > due 
           ? due +' passed: <b>send reminder to A</b>'
           : due +' not passed: <b>send reminder to B</b>';
}

function convertToDate(dateString) {
    return new Date(dateString.split("/").reverse().join('/'));
}
<div id="result"></div>
like image 118
KooiInc Avatar answered May 10 '26 10:05

KooiInc