how to compare with javascript two datepicker fields

Asked

Viewed 1,130 times

0

I need to compare two fields in my html that are with datepicker. Follow my code below:

    var inicio = $("#Periodo_De").datepicker("getDate");
    var final = $("#Periodo_Ate").datepicker("getDate");

    if (inicio > final) {
      console.log('inicio é maior que final');
    }
  • What’s going wrong? An error appears on the console?

  • From what I understand he is comparing in the American pattern and my datepicker this in Brazilian... I think I will have to compare day/month/year to work

  • 1

    I guess if you format ANOCOMPLETO-MES-DIA for this type of check can work.

  • According to the documentation no, this method returns object Date (and when you compare 2 of these, you’re comparing a value in milliseconds).

1 answer

0


I think you should know that for the datapicker working you should add his libs...

In this case, besides the JQuery I’m using the library JQuery-UI:

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>

HTML code:

<input type="text" id="inicio" name="inicio">
<input type="text" id="final" name="final">

<input type="button" id="testar" name="testar" value="testar">

JS Code:

$(document).ready(function () { 
    $('#inicio').datepicker({ dateFormat: 'dd/mm/yy' }).val();
    $('#final').datepicker({ dateFormat: 'dd/mm/yy' }).val();
});

$("#testar").click(function() {
    var inicio = $('#inicio').val();
    var final = $('#final').val();

    if (inicio > final) {
        alert('inicio é maior que final');
    }else{
        alert('final é maior que inicio');
    }
});

Here at the Jsfiddle an example of datapicker working the way you need...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.