Calculation of interval of 2 dates

1

Personal how do I separate dates and calculate the range of 2 dates and in the daterangepicker? Ex: I put the default selector

$('input[name="daterange"]').daterangepicker();

I select the date range between them and the beginning stays in the input dtInicio the end of the date goes to the dtFim and appears the amount of days chosen in an input qtdDias in JS?

    
asked by anonymous 18.03.2017 / 09:31

1 answer

2

You could make your code better fit your question . If you are this daterangepicker you are using you can do so to calculate the days of difference:

const milis_day = 1000 * 60 * 60 * 24;

$(function() {
    $('input[name="daterange"]').daterangepicker();
});
$('input[name="daterange"]').on('apply.daterangepicker', function(ev, picker) {
  var pick1 = new Date(picker.startDate.format('YYYY-MM-DD')); // primeira data
  var pick2 = new Date(picker.endDate.format('YYYY-MM-DD')); // segunda data
  var utc1 = Date.UTC(pick1.getFullYear(), pick1.getMonth(), pick1.getDate());
  var utc2 = Date.UTC(pick2.getFullYear(), pick2.getMonth(), pick2.getDate());
  
  var diff = Math.floor((utc2 - utc1) / milis_day)
  $('#qtdDias').val(diff);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scripttype="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/3/css/bootstrap.css" />
 
<!-- Include Date Range Picker -->
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />



<input type="text" name="daterange" value="" />
<br><br>Dias de diferença: <br>
<input id="qtdDias" readonly disabled>
    
18.03.2017 / 10:57