compare two dates in jQuery

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 content of my alert comes invalid date .

Date in the format dd / mm / yyyy

All right?

    
asked by anonymous 28.04.2017 / 06:31

1 answer

1

You can compare the complete 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**/
}
    
28.04.2017 / 14:10