How to compare two dates in Javascript or jQuery

Asked

Viewed 12,530 times

5

I’m trying to compare two dates from fields text, turning them into objects Date, as follows (the first function is to format the field input with XX/XX/XXXX):

function formatar(mascara, documento){
    var i = documento.value.length;
    var saida = mascara.substring(0,1);
    var texto = mascara.substring(i);
    if (texto.substring(0,1) != saida){
        documento.value += texto.substring(0,1);
    }
}

if(new Date('#datafinal') <= new Date('#datainicial'))
{

alert("A data inicial é maior que a data final");
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" maxlength="10" placeholder="dd/mm/aaaa"
                       OnKeyPress="formatar('##/##/####', this)" id="datainicial">
<br>
                <input type="text" maxlength="10" placeholder="dd/mm/aaaa"
                       OnKeyPress="formatar('##/##/####', this)" id="datafinal">

But it’s not working. I think it might be because of the format that comes from input, but I’m not sure. I did a search on Soen and there are several questions with many answers, but none of the ones I saw could solve for me.

Basically, I need when the person finishes typing (before clicking send button) to return a alert if the final date is less than the initial one. Some light?

1 answer

3


I suggest you switch to HTML onkeypress because that way the input value is passed to the function with the last key. With onkeypress value does not have the new number yet.

In Javascript you can do so:

var datainicial = document.getElementById('datainicial');
var datafinal = document.getElementById('datafinal');

function formatar(mascara, documento) {
    var i = documento.value.length;
    var saida = mascara.substring(0, 1);
    var texto = mascara.substring(i);
    if (texto.substring(0, 1) != saida) {
        documento.value += texto.substring(0, 1);
    }
    verificar();
}

function gerarData(str) {
    var partes = str.split("/");
    return new Date(partes[2], partes[1] - 1, partes[0]);
}

function verificar() {
    var inicio = datainicial.value;
    var fim = datafinal.value;
    if (inicio.length != 10 || fim.length != 10) return;

    if (gerarData(fim) <= gerarData(inicio)) alert("A data inicial é maior que a data final");
}

Example: http://jsfiddle.net/3z247n2o/

Use a function to convert this string to date:

function gerarData(str) {
    var partes = str.split("/");
    return new Date(partes[2], partes[1] - 1, partes[0]);
}

and then compare it to the logic you already had:

if (gerarData(fim) <= gerarData(inicio))

If you want to use the function verificar() integrated in the other validation code of the form you can use it like this, giving return true or false:

function verificar() {
    var inicio = datainicial.value;
    var fim = datafinal.value;
    if (inicio.length != 10 || fim.length != 10) return false;

    if (gerarData(fim) > gerarData(inicio)) return true;
    alert("A data inicial é maior que a data final");
    return false;
}
  • 1

    This script really helped me, thanks @Sergio.

Browser other questions tagged

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