I'm trying to compare two datepicker
dates and see if they are more than 7 days apart.
How would I do this?
I would normally just see if their difference is greater than 7, but that won't account for months and such.
Here is my code:
var datepickerBegin = $("#datepicker_start").val();
var datepickerEnd = $("#datepicker_to").val();
if (datepickerBegin - datepickerEnd > 7) {
alert('more than a week apart!')
}
Any tips??
In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.
Use $("#datepicker_xxx").datepicker("getDate")
to get the picked date as a Date
. Then it's just a matter of
end - begin > 7 * 86400 * 1000
Try this, DatePicker has a handy formatDate function which i've used to compare mm/dd/yy dates:
$.datepicker.formatDate("dd/mm/yy",new Date("09/01/2014")) < $.datepicker.formatDate("dd/mm/yy", new Date("10/01/2014")); // Returns true
$.datepicker.formatDate("dd/mm/yy",new Date("10/01/2014")) < $.datepicker.formatDate("dd/mm/yy", new Date("10/01/2014")); // Returns false
$.datepicker.formatDate("dd/mm/yy",new Date("11/01/2014")) < $.datepicker.formatDate("dd/mm/yy", new Date("10/01/2014")); // Returns false
// Check the date range, 86400000 is the number of milliseconds in one day
var difference = (datepickerEnd- datepickerBegin ) / (86400000 * 7);
if (difference < 0) {
alert("The start date must come before the end date.");
return false;
}
if (difference <= 1) {
alert("The range must be at least seven days apart.");
return false;
}
return true;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With