Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two datepicker dates using jQuery

This is my code:

var $from = $("#fromDate").datepicker('getDate');
var $to = $("#toDate").datepicker('getDate');
if($from > $to)
   alert("from date shouldn't greater than To date");

It is working if it is two dates in the same year. Otherwise, for example fromDate='1/12/2012'(dd/mm/yyyy) toDate='18/6/2013'(dd/mm/yyyy), while you check the condition, it is not working. It throws an alert, which is given.

like image 912
Kanagaraj Vadivel Avatar asked Jun 18 '13 13:06

Kanagaraj Vadivel


3 Answers

Date.parse(fromDate) > Date.parse(toDate)

Example

var sDate = $('#EFT_FRM_DATE').val();
var eDate = $('#EFF_TO_DATE').val();

if (Date.parse(sDate) > Date.parse(eDate) || Date.parse(sDate) == Date.parse(eDate)) {
   ShowMessage(CurrencySetupExchangeIndex.EndDateGreaterStartDate, 'Error');
   //alert
   return false;
   return;
}

Simplified statement:

if (Date.parse(sDate) >= Date.parse(eDate)) {...
like image 138
Asif Raza Avatar answered Nov 10 '22 11:11

Asif Raza


Auto limit your dates instead. In this example the second combo box won't allow you to pick a lower date than the one you pick on the first one.

$(document).ready(function() {

  $("#txtFromDate").datepicker({

    numberOfMonths: 2,

    onSelect: function(selected) {
      $("#txtToDate").datepicker("option", "minDate", selected)
    }
  });

  $("#txtToDate").datepicker({

      numberOfMonths: 2,

      onSelect: function(selected) {
         $("#txtFromDate").datepicker("option", "maxDate", selected)

      }
  });
});

Here is a working demo.

like image 45
isJustMe Avatar answered Nov 10 '22 10:11

isJustMe


You need to use this to get the day/month/year:

var day1 = $("#datepicker").datepicker('getDate').getDate();
var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;
var year1 = $("#datepicker").datepicker('getDate').getFullYear();

After that, you can compare the values.

like image 3
Setup Avatar answered Nov 10 '22 12:11

Setup