12

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kanagaraj Vadivel
  • 473
  • 2
  • 7
  • 14

5 Answers5

31

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
isJustMe
  • 5,452
  • 2
  • 31
  • 47
  • 2
    Thanks a lot! You saved my day! – Adrian P. Aug 03 '15 at 15:19
  • I know I'm adding a comment for an old post, but is this able to work without the Jquery UI? Right now I use Jquery 1.9.1 and am trying to use datepicker but when I uncheck UI from your JSFiddle, it stops working. Any ideas? – Mkalafut Jun 08 '16 at 14:03
  • Very useful! but I want to know how to prevent select the same day in `txtFromDate` field? Thanks! – candlejack Jul 03 '16 at 03:43
3

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Setup
  • 330
  • 2
  • 21
3
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)) {...
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Asif Raza
  • 971
  • 6
  • 14
0

$(document).ready(function() {
    $("#startdate").datepicker({
            todayBtn:  1,
            format: "dd-mm-yyyy",
            startDate: '1d',
            autoclose: true,
    }).on('changeDate', function (selected) {
        var minDate = new Date(selected.date.valueOf());
        $('#enddate').datepicker('setStartDate', minDate);
        if($('#enddate').val() != "" && ($("#enddate").datepicker("getDate") == null || Date.parse($("#enddate").datepicker("getDate"))< Date.parse($("#startdate").datepicker("getDate")))) {
            var date = new Date($("#startdate").datepicker("getDate")).toLocaleDateString();
            date = date.split("/")
            date = date[0] + "-" + date[1] + "-" + date[2]
            $('#enddate').val(date)
        }
    });

    $("#enddate").datepicker({
        format: "dd-mm-yyyy",
        autoclose: true,
    })
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    An answer without an explanation or details is usually of no use to many people. It'd be great to add details on how you solved this – mw509 Mar 16 '20 at 09:11
0

Even though this person's issue was resolved, I still want to answer the question in the title, "How to compare two datepicker dates using jQuery"

I prefer getting the timestamps of the dates and then just comparing them since they're numbers, that way I don't have to mess around with comparing months, years, leap years, etc. I just want to see which date is chronologically first.

To do that, you can use the getTime() function on the datepicker object like this: $from = $("#fromDate").datepicker('getDate').getTime();

This function returns the number of milliseconds since January 1st, 1970, 00:00:00.000 GMT. If the number is smaller, that means it's closer to that date in the past. If it's bigger, then it's farther away (in the future).

See below for a working snippet.

// Init datepickers
$('.datepicker').datepicker();
$('button').on('click', compareDates);

function compareDates() {
  var $from = $("#fromDate"),
    $to = $("#toDate");
  if ($from.val() && $to.val()) {
    var from = $from.datepicker('getDate').getTime(),
      to = $to.datepicker('getDate').getTime(),
      response = 'These dates are the same, <strong><em>invalid!</em><strong>';
    if (from > to) {
      response = 'To happens first, <strong><em>invalid!</em><strong>';
    } else if (from < to) {
      response = 'From happens first, valid!';
    }
    $('#output').html(response);
  }
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>

<p>From Date: <input type="text" id="fromDate" class="datepicker"></p>
<p>To Date: <input type="text" id="toDate" class="datepicker"></p>

<p><button>Compare Dates</button></p>

<p id="output">Enter Dates and then click the button to compare them</p>
AuRise
  • 2,253
  • 19
  • 33