Geoff
Geoff

Reputation: 6639

Javascript moment js split time based on hours from current time to previous midnight

What am looking forward to get is a split of time from current time to yesterdays midninght split by one hour

so that is

eg: if now its 03:34

so i would like to get this

var durations = [
     {from:03:00, to:03:34},
     {from:02:00, to:03:00},
     {from:01:00, to:02:00},
     {from:00:00, to:01:00}
 ]

SO from the above example the value of 03:34 is the current time

SO far i have been able to get the first segment via

{from:moment().startOf('hour'), to:moment()}

Now am stuck on how to split the other durations with a difference of 1 hour each

So its something like

let hours_from_midnight = moment.duration(end.diff(moment().startOf('day'))).asHours();

But now how do i proceed to use the number of hours from midnight to split the next durations and achieve the durations desired

Upvotes: 0

Views: 687

Answers (1)

Aankhen
Aankhen

Reputation: 2272

What you need to do is keep subtracting an hour and cloning the date, as all the methods mutate the existing object:

function periods(initialTime) {
  // our lower bound
  const midnight = initialTime.clone().startOf("day");
  // our current period start
  const periodStart = initialTime.clone().startOf("hour");

  const periods = [];

  if (!(periodStart.isSame(initialTime))) {
    // only add the last period if it isn't empty
    periods.push({ start: periodStart.clone(), end: initialTime });
  }

  while (periodStart.isAfter(midnight)) {
    // the last start is our new end
    const to = periodStart.clone();
    // our new start is one hour earlier
    const from = periodStart.subtract(1, "hour").clone();

    periods.push({
      from,
      to
    });
  }

  return periods;
}

console.log(periods(moment("03:34", "HH:mm")));
console.log(periods(moment("18:00", "HH:mm")));

Upvotes: 2

Related Questions