Get hours between two times in moment.js

Viewed 291

I try like this :

let fromTime = '17:00'
let toTime = '20:00'
let a=[]
for(let i=parseInt(fromTime);i<parseInt(toTime);i++){
  a.push({time: i+':00'})
}
console.log(a)

It works. But It is the best way to do it?

Is the best way using moment js?

2 Answers

Kinda, but you can get this result much better. first convert your time as moment.js object then get difference between fromTime and toTime then get diff as hours and finally add one hour for difference in loop.

let fromTime = moment('17:00', 'HH:mm');
let toTime = moment('20:00', 'HH:mm');
let duration = moment.duration(toTime.diff(fromTime));
let diff = duration.hours();
let array = [];

for (i = 0; diff > i; i++) {
  let result = moment(fromTime).add(i, 'hours').format('HH:mm')
  array.push({
    result
  })
}

console.log(array)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>

One thing, it make sense to get exact hours between from and to times, so you can set i=1 to get only:

[
  {
    "result": "18:00"
  },
  {
    "result": "19:00"
  }
]

Instead of moment js i would recommend to use js-joda library.

import {LocalTime } from '@js-joda/core'

const start = LocalTime.parse("10:00")
const end = LocalTime.parse("20:30")

const times = [];

for (let time = start; time.compareTo(end) < 0; time = time.plusHours(1) ) {
  times.push(time.toString());
}

console.log(times);

https://js-joda.github.io/js-joda/manual/LocalTime.html

Related