Reputation: 2724
I am trying to compare two dates, one is in text box written as YYYY-MM-DD
and other is jquery Datepicker instance
I am calling the function with a custom wrapper function
datePicker('#edd', {onSelect: function(str, obj){ check_if_edd_less_OD(str, obj); }});
and below is the JS function to compare dates
function check_if_edd_less_OD(s, o) {
console.clear();
var eddDate = new Date();
eddDate.setDate(o.selectedDay);
eddDate.setMonth(o.selectedMonth);
eddDate.setYear(o.selectedYear);
orderDate = $('#orderdate').val().split('-');
console.log(orderDate);
var odDate = new Date();
odDate.setDate(parseInt(orderDate[2], 10));
odDate.setMonth(parseInt(orderDate[1], 10));
odDate.setYear(parseInt(orderDate[0], 10));
console.log(eddDate);
console.log(odDate);
if (odDate.getTime() < eddDate.getTime()) {
console.log('You shall Pass');
} else {
console.log('You shall NOT Pass');
}
}
as of today, the orderdate input is set to 2013-03-07, if I select 5 APR 2013 from datepicker it dont work
following is the output of console
["2013", "03", "07"]
Date {Fri Apr 05 2013 16:55:23 GMT+0500 (Pakistan Standard Time)}
Date {Sun Apr 07 2013 16:55:23 GMT+0500 (Pakistan Standard Time)}
You shall NOT Pass
as you can see console.log(eddDate);
is giving correct output but console.log(odDate);
is giving me 7th April 2013.
Question: Why this is such a behavior?
Upvotes: 0
Views: 204
Reputation: 664876
The month counting of Date
objects is zero-based (January:0, …, April:3). Not sure what format that o.selectedMonth
is in, but the parsed YYY-MM-DD date should be changed to
odDate.setMonth(parseInt(orderDate[1], 10)-1);
Btw, you don't need to call getTime()
before comparing two Date
objects against each other, they will automatically be casted to that number.
Upvotes: 1