Calculate value according to selected dates

Asked

Viewed 372 times

3

I have to make a code that calculates Reais according to 2 dates reported. I have 2 inputs of the kind text to inform a data in format dd/mm/yyyy. The input To is from data inicial and the B is the data final. The user will inform on input A for example 20/05/2015 and on input B will be 03/05/2015. The difference then is 13 days and need to multiply by 10 (that would be the price in Reais), thus totaling R$ 130,00 Real. I want to arrive at the following, the user inform the two dates the calculation is made automatic and displayed in a <div>. I don’t have any code ready, but I’m having extreme difficulty making that code.

2 answers

2

To calculate the days is like this:

function diferencaEntreDias(dataIni, dataFim){//recebe a data no formato MM/dd/yyyy  
    var ONE_DAY = 1000 * 60 * 60 * 24;//Variável que representa um dia em milissegundos  
    var date_ini_ms = new Date(dataIni).getTime();//variável que representa a data incial em ms  
    var date_fim_ms = new Date(dataFim).getTime();//variável que representa a data final em ms  
    var diferenca = date_fim_ms - date_ini_ms;//diferenca, em ms, entre as datas  
    return Math.round(diferenca/ONE_DAY);//diferenca, em dias, entre as datas  
}

To calculate just do:

window.alert(qtdDias * 10);

remembering that it is an Alert for you to see the value of the calculation.

The example to update the DIV is this:

<!DOCTYPE html>
<html>
<head>
    <title>teste</title>
    <meta charset="UTF-8" />
    <script type="text/javascript">
        function gravar(){
            var titulo = document.getElementById("txtTitulo").value;
            var subtitulo = document.getElementById("txtSubtitulo").value;
            var div = document.getElementById("divResultado");

            div.innerHTML = "<h1>" + titulo +"</h1>"+ "\n" + subtitulo;
        }
    </script>
</head>
<body>
    <div>
        <label>Título:</label>
        <input type="text" id="txtTitulo"/>
        <label>Subtítulo:</label>
        <input type="text" id="txtSubtitulo"/>
        <button id="btnEnviar" onclick="diferencaEntreDias(passeAsDatasAqui)" >Gravar</button>
    </div>
    <div id="divResultado">
    </div>
</body>
</html>

As you can see is an example you will need to understand to mount it properly but this is the basis.

2

You can use the library Momentjs to do the parse and see how many days have passed.

var inicial = moment('1/02/2015', 'DD/MM/YYYY'),
    final =   moment('14/02/2015', 'DD/MM/YYYY'),
    diasPassados = final.diff(inicial, 'days');

alert('Dias passados: ' + diasPassados); // Dias passados: 13
alert('Valor do frete: R$' + (diasPassados * 10) + ',00'); // Valor do frete: R$130,00
<script src='http://momentjs.com/downloads/moment.min.js'></script>

The function diff provides various information of differences between dates. When used by sending the argument 'days', is returned the amount of days passed between a date and another.

function byId(el) {
  return document.getElementById(el)
};

function isNullOrEmpty(el) {
  return el.value == null || el.value == '';
}

var $inicial = byId('inicial'),
  $final = byId('final'),
  $frete = byId('frete'),
  $calcular = byId('calcular');

$calcular.addEventListener('click', function() {

  var valorFrete = '00';

  if (!isNullOrEmpty($inicial) && !isNullOrEmpty($final)) {

    var inicial = moment($inicial.value, 'DD/MM/YYYY'),
        final =   moment($final.value,   'DD/MM/YYYY');

    // isValid é uma função da própria biblioteca MomentJS
    // para verificar se uma data é válida.
    if (inicial.isValid() && final.isValid())
      valorFrete = final.diff(inicial, 'days') * 10;
  }

  $frete.innerHTML = 'R$' + valorFrete + ',00';
});
<script src='http://momentjs.com/downloads/moment.min.js'></script>

<label for='inicial'>Data Inicial</label>
<input id='inicial' type='text' placeholder='10/02/2015' />
<label for='final'>Data Final</label>
<input id='final' type='text' placeholder='10/02/2015' />

<button id='calcular'>Calcular</button>
<p id='frete'></p>

  • Wow, thanks is halfway there. But there is still one thing missing that I think for me will be the most difficult, which is the question of only calculating when the user fills the two date fields To and B, how could I do that? It’s being the hardest now

  • Includes a simple example without many validations. @Alissonacioli

Browser other questions tagged

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