Calculate difference between two dates to validate date fields

Asked

Viewed 42,573 times

4

I needed to find a mechanism to limit a search no longer than 3 months.

I have two dates, I want to validate if they are within the defined parameters.

have this code() I am using type date and datepicker to run on various browsers

  <script src="data/js/moment.js" type="text/javascript"></script>

                       <script type="text/javascript">
                    $("#pesquisa").on("submit", function (event) {
                        event.preventDefault();
                     var start= new Date(document.getElementById("datainicio").value);
                       var end = new Date(document.getElementById("datafim").value);
                    var dr    = moment.range(start, end);

                    dr.diff('months'); // 3
                    dr.diff('days'); // 92
                   alert( dr.diff();) // 7945200000

                  //   mostrarinfo();
            });
  • 1

    Related: http://answall.com/q/13046/227

  • I’ve seen it, but it doesn’t work

  • 1

    To better help colleagues answer you, try to explain what you’ve tried. Provide sample codes of attempts you made and where or what isn’t working.

  • for now I have only this, I will fetch the fields var dateinicio= Document.getElementById("start date"); var datafim = Document.getElementById("end date"); var datestart= new Date(); var dateend= new Date();

  • To solve this in an elegant and quick way use the momentjs.

  • See this library that has example of how to calculate the difference.

  • thanks :) I will try to put here the solution

  • 1

    None of the answers offered will satisfy you?

Show 3 more comments

3 answers

9

  • Great solution, no external resource.

  • No explanation or comments in the code

  • it’s true you want me to explain?

  • How do you calculate negative date. Example today are 08/02/2020, if I compare with 10/02/2020 are +2 days. Now if I compare with 06/02/2020 it should be -2.

5

In the JavaScript dates are valued according to the amount of milliseconds from 01/01/1970 00:00:00 GMT-0. By subtracting one date from another you will have the difference between dates in milliseconds.

The simplest way is to create the end date limit, based on the start date. I consider this path the simplest because it does not involve much calculation, since Javascript always generates a valid date. So you can simply add 3 months to the start date without worrying about turn of year or leap year, for example.

Comparing end date with end date

var dataInicio = new Date(document.getElementById("datainicio").value);
var dataFim = new Date(document.getElementById("datafim").value);
var limiteFim = new Date(dataInicio.getFullYear(),
                         dataInicio.getMonth() + 3,
                         dataInicio.getDate());

return !(dataFim > limiteFim);

Calculating the difference between the dates

var dataInicio = new Date(document.getElementById("datainicio").value);
var dataFim = new Date(document.getElementById("datafim").value);
var diffMilissegundos = dataFim - dataInicio;
var diffSegundos = diffMilissegundos / 1000;
var diffMinutos = diffSegundos / 60;
var diffHoras = diffMinutos / 60;
var diffDias = diffHoras / 24;
var diffMeses = diffDias / 30;

return !(diffMeses > 3);
  • Yes, that’s true, but as it turns out they are between a period of 3 months?

  • Matemágica, my friend ;) Create the end date limit and compare with the end date informed. If the end date limit is lower is outside the period. if (end > start.setMonth(start.getMonth() + 3)) { return false; }

  • Yes, I know how it’s done, the AP is not. My comment was an invitation to you to improve your response in order to make it more complete..

  • 1

    Supplemented ;)

  • I need so much :p

  • It’s pure Javascript. I find it hard to resort to a library for a simple comparison of dates. In addition to answering the question I gave a broad explanation allowing this answer to solve other similar problems, not only if the difference between the two dates is less than or equal to 3 months.

Show 1 more comment

-1

Simple and functional code. Use in various systems my:

$("#data-termino-ausencia").focusout(function(){
    var dtI = $(".data-inicio-ausencia").html().split('/');
    var dtF = $("#data-termino-ausencia").val().split('/');
    dia_I = dtI[0];
    dia_F = dtF[0];
    mes_I = dtI[1];
    mes_F = dtF[1];
    ano_I = dtI[2];
    ano_F = dtF[2];
    var calculoDia = dia_F - dia_I;
    var calculoMes = mes_F - mes_I;
    var calculoAno = ano_F - ano_I;

    if(calculoDia < "0" || calculoMes < "0" || calculoAno < "0"){
        BackOffice.alert("A data de término não pode ser anterior a data de inicio.", "Aviso", function(){
            $("#data-termino-ausencia").val("");
            $("#data-termino-ausencia").focus();
            BackOffice.closeModal('.modal', true);
        });
    } else if (calculoDia < "0" || calculoMes >= "0" || calculoAno >= "0") {       
        $(".outros-ausencia").focus();
    } else if (calculoDia <= "0" || calculoMes >= "0" || calculoAno >= "0") {
        $(".outros-ausencia").focus();<br>
    }
})

Browser other questions tagged

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