Calculate value according to selected dates

3

I have to make a code that calculates Reais according to 2 dates informed. I have 2 inputs of type text to report a data in dd/mm/yyyy format. The A input is data inicial and the B is the data final . The user will inform on input A for example 05/20/2015 and input B will be 03/05/2015. The difference is then 13 days and I need to multiply by 10 (which would be the price in Reais), thus totaling R$ 130,00 Reais. I want to get to the next, the user informing the two dates the calculation is done automatic and displayed in a <div> . I do not have any code ready, but I'm having a hard time making this code.

    
asked by anonymous 19.05.2015 / 20:59

2 answers

2

To calculate the days it looks 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 that you will need to understand to mount it correctly but that is the basis.

    
19.05.2015 / 21:20
2

You can use the MomentJS library to parse and check 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 diff function provides a lot of difference information between dates. When used by sending the argument 'days' , the number of days passed between one date and another is returned.

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>
    
19.05.2015 / 21:48