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 (tod
Solution 1:
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');
functionmainFunc(due) {
due = due ? convertToDate(due) : newDate;
returnnewDate > due
? due +' passed: <b>send reminder to A</b>'
: due +' not passed: <b>send reminder to B</b>';
}
functionconvertToDate(dateString) {
returnnewDate(dateString.split("/").reverse().join('/'));
}
<divid="result"></div>
Solution 2:
Just return it in milliseconds format
functionconvertToDate(dateString) {
var dateData = dateString.split("/");
return +newDate(newDate().setFullYear(dateData[0], dateData[1] - 1, dateData[2]));
}
And also change var today = new Date();
to var today = +new Date();
. Now it should work. +
here converts Date
object to milliseconds.
Solution 3:
The best way to compare two date is to instanciate them with same object, here you must use Date object.
functionmainFunc(){
var firstDate = newDate( dueDate = "30/12/2014" );
today = newDate();
if( today > firstDate ){
//...
}
else{
//...
}
}
Solution 4:
I will recomend momentjs lib to parse, validate, manipulate, and display dates in JavaScript.
var firstDate = moment("30/12/2014", "DD/MM/YYYY")
var today = moment();
// Format to Unix Timestamp to compareif(today.format('X') > firstDate.format('X')){
//send reminder to A
}else{
// send reminder to B
}
Here is the link http://momentjs.com/
Post a Comment for "How To Compare Dates In Javascript With Two Different Format?"