Simple comparison between dates

7

I need a simple comparison between dates in javascript so the end date can not be less than the start date. I found some scripts on the internet and tried to adapt to mine, but as I know practically nothing, it did not work.

Follow the script I'm adapting.

  <script language="javascript">
function checarDatas(){
var form_insere = document.form_insere;

var data_1 = form_insere.datainicial.value;
var data_2 = form_insere.datafinal.value;
var Compara01 = parseInt(data_1.split("/")[2].toString() + data_1.split("/")[1].toString() + data_1.split("/")[0].toString());
var Compara02 = parseInt(data_2.split("/")[2].toString() + data_2.split("/")[1].toString() + data_2.split("/")[0].toString());

if (Compara01 > Compara02) {
   alert("Data não pode ser maior que a data final");
   return false;
}
else {
    return true
}
 }
    </script>

I also put onsubmit="return checarDatas()" in the form tag. The goal is when the user enters a start date (05/07/2014) and then the end date (04/06/2014) triggers an alert indicating that the dates are wrong and do not let him submit the form until he returns and corrects. Thanks, and I accept any kind of suggestions.

    
asked by anonymous 06.05.2014 / 20:36

2 answers

10

I think you just need to create date objects and compare them.

function checarDatas() {
    var form_insere = document.form_insere;

    var data_1 = new Date(form_insere.datainicial.value);
    var data_2 = new Date(form_insere.datafinal.value);
    if (data_1 > data_2) {
        alert("Data não pode ser maior que a data final");
        return false;
    } else {
        return true
    }
}

These validations can be more or less complex depending on what you want to do. I suggest joining a check in case the dates have not been chosen. In its simplest form would be:

if (!data_1 || !data_2) return false;

Example

    
06.05.2014 / 20:39
3

Complementing:

There is a great library, called Moment.js , specially designed to handle dates / times / timezones. Depending on the need to manipulate dates in your project, it may become interesting.

An example of comparing dates using Moment.js:

var agora = moment();
var amanha = moment().add('days', 1);

if (agora < amanha) {
    // alguma coisa
}
else {
    // outra coisa
}
    
06.05.2014 / 22:18