compare two dates in jQuery

Asked

Viewed 973 times

1

Good morning

$("#salvar").on('click', function(e){
        var startDate = new Date($('#data_abertura').val());
        var endDate = new Date($('#data_encerramento').val());

        alert(startDate);

        if (startDate > endDate){
            $("#error").html("Data de Abertura deve ser menor ou igual a Data de Encerramento");
            $('#myModal').modal("show");
            e.preventDefault();
        }

    });

the contents of my alert comes invalid date.

Date in dd/mm/YYYY format

All right?

  • You can display the HTML of data_abertura and data_encerramento? you know its value?

1 answer

1

You can compare the full date.

Example

var dtInicio = document.getElementById("data_abertura").value;
var dtFim = document.getElementById("data_encerramento").value;

var dtBegin = dtInicio.split("/");
    var bdia = dtBegin[0];
    var bmes = dtBegin[1];
    var bano = dtBegin[2];
var startDate = new Date(bmes +"/"+bdia+"/"+bano)


var dtFinish = dtFim.split("/");
    var fdia = dtFinish[0];
    var fmes = dtFinish[1];
    var fano = dtFinish[2];
var endDate = new Date(fmes +"/"+fdia+"/"+fano)    

if ( new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate()) > 
         new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate()) ){
   /*** seu codigo**/
}

Browser other questions tagged

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