Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Convert an array of dates into a date range containing Month, days, hours accumulated in JavaScript

I have a list of dates that I need to convert into a date range, slicing out the Month values that aren't on the first date of the date ranges, while also adding the hours accumulated for the days within the day portion.

My example array is:

   ["Nov 23 2021 8 hrs",
    "Nov 24 2021 8 hrs",
    "Nov 27 2021 8 hrs",
    "Dec 3 2021 8 hrs"]

I am trying to get the end array to look like this:

["Nov 23-24 2021 16hrs, Nov 27 2021 8hrs, Dec 3 2021 8hrs"]

So far I was able to get the dates to concatenate correctly with this code just passing in an array that contains only numbers

 const getDayRanges = (dayArr) => {
  var ranges = [],
    rstart,
    rend;
  for (var i = 0; i < dayArr.length; i++) {
    console.log("days" ,dayArr[i])
    rstart = dayArr[i];
    rend = rstart;
    while (dayArr[i + 1] - dayArr[i] == 1) {
      rend = dayArr[i + 1]; // increment the index if the numbers sequential
      i++;
    }
    ranges.push(rstart == rend ? rstart + "" : rstart + " to " + rend);
  }
  return ranges;
};

But I have not been about to figure out how to slice out the Months correctly to place them in a new array with the hyphenated date numbers, let alone how to then add up all of the hours portion that align with the dates that are concatenated.

Any help would be extremely appreciated.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!