Get dates that are between a start date and a final date Moment js?

0

Cordial greeting colleagues, is that I'm using momentjs for handling dates in my application, my problem is that I need to compare a start date and an end date, then fill an array with the dates you are among these, eg if I have a start date and an end date 2018/09/07 2018/09/10 then the values of my array should be the following: array = [ '2018/09/08', '2018/09/09'], probe using the diff function I found in the documentation:

var moment = require('moment');
           let init_date = moment(self.crono.init_date);
           let end_date = moment(self.crono.end_date);

           console.log(end_date.diff(init_date, 'days'), ' dias de diferencia');

but in doing this I get the days of difference, but I do not get the dates as such that I need.

How could I fill the array with the dates I need?

    
asked by Kevin Burbano 08.09.2018 в 02:19
source

1 answer

1

I should serve you like this:

$('#btn').on('click', function(){
    var ini = moment(document.getElementById('start').value);
    var fin = moment(document.getElementById('end').value);
    
    if(ini != undefined && fin != undefined){
      $('ul').empty();
      var fechas = [];
      
      while (ini.isSameOrBefore(fin)) {
        fechas.push(ini.format('M/D/YYYY'));
        ini.add(1, 'days');
      }
      
      $.each(fechas, function(i, v){
        var d = moment(v).format('DD-MM-YYYY');
        $(".row ul").append('<li class="text-success">' + d + '</li>');
        //console.log(d);
      })
    }
  })
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
  <div class="row">
    <div class="col-md-4">
      <label class="control-label col-md-4">Inicio</label>
      <div class="col-md-12">
        <input type="date" class="form-control" id="start">
      </div>
    </div>

    <div class="col-md-4">
      <label class="control-label col-md-4">Fin</label>
      <div class="col-md-12">
        <input type="date" class="form-control" id="end">
      </div>
    </div>

    <div class="col-md-4">
      <div class="col-md-12">
        <button type="button" class="btn btn-primary col-md-8" style="margin-top:33px; margin-left:-20px" id="btn" onclick="obtener()">Obtener</button>
      </div>
    </div>
  </div>
  
  <div class="row mt-2">
    <ul></ul>
  </div>
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

You tell us how you are doing

    
answered by 08.09.2018 / 03:49
source