Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Datepicker Dates Javascript

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??

like image 974
streetlight Avatar asked Oct 10 '12 13:10

streetlight


People also ask

How do you compare two date objects in JavaScript?

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.


3 Answers

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
like image 181
Gustav Barkefors Avatar answered Nov 02 '22 10:11

Gustav Barkefors


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
like image 44
Alex Avatar answered Nov 02 '22 09:11

Alex


// 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;
like image 2
Milind Anantwar Avatar answered Nov 02 '22 09:11

Milind Anantwar