Range between two hours momenjs (angularjs)

1

I am trying to find ranges between two given hours, in If what I want is to do the following:

I have h1 = 20:00:00 and h2 = 20:30:00

What I want is for the final result to equal this:

20: 00: 00--20: 10: 00--20: 20: 00--20: 30: 00 This means adding 10 minutes to the given time

This is my code:

.controller('General', function($scope){
   $scope.h1=moment("18:00:00",'HH,mm,ss').format('HH-mm-ss');
   $scope.h2=moment("21:00:00",'HH,mm,ss').format('HH-mm-ss');

  var rangoMinutos = function(h1, h2) {
      var rango= [];

      while (h1 <= h2) {
          rango.push(h1);
          h1.add(1,'hours');//NO SE SI ESTE BIEN ESTO
      }
      return rango;
  };

  var results1 = rangoMinutos($scope.h1, $scope.h2);
  alert(results1)//ver resultado de los rangos
})
    
asked by Dimoreno 05.08.2016 в 05:57
source

2 answers

0

The main problem I see in your code is that when generating the array you are adding the same object moment n times, so when reading it you will get n equal elements with the same time.

If you are going to create an array of moment objects you should create a new object each time you add an element to the array.

Take a look at this example:

function calculateRange(start, end, minutes){
  var range = [];
  for(var hour = moment(start); hour.isBefore(end); hour.add(minutes, 'minutes') ){
    range.push(moment(hour));
  }
  range.push(moment(end));
  return range;
}


$(function(){
  $('#calculate').click(function(){
    var start = moment($('#startHour').val(), 'H:mm:ss');
    var end = moment($('#endHour').val(), 'H:mm:ss');
    var rangeArray = calculateRange(start, end, 10);
    var result = rangeArray.map(function(hour){ return hour.format('HH:mm:ss'); });
    $('#result').text(result.join(' --- '));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Start: <input type="text" id="startHour" value="08:14:00"><br />
End: <input type="text" id="endHour" value="14:34:57"><br />
<button id="calculate">
Calculate
</button><br /><br />
<div id="result">

</div>
    
answered by 05.08.2016 / 08:36
source
0

I do not know MomentJS, but the first thing you should do is convert the two hours to a format that you can really compare their different.

const range = (start, end, interval) => {
    let s = start.split(':').map(s => s)
    let e = end.split(':').map(e => e)
    let time = []
    while (!(s[0] === e[0] && s[1] > e[1])) {
        time.push(s[0] + ':' + (s[1] < 10 ? '0' +s[1] : s[1]))
        s[1] += interval
        if (s[1] > 59) {
            s[0] += 1
            s[1] %= 60
        }
    }

    return time
}
console.log(range('18:80', '21:00', 30))
    
answered by 05.08.2016 в 08:23