Can you provide guidance on how to divide a series of dates and times into an array based

Given a startDate and an endDate, I am looking to split them into an array of time slots indicated by the duration provided. This is not a numerical pagination, but rather dividing a time range.

In my TypeScript code:

startDate: Date;
endDate: Date;
timeSlots: moment.Duration = moment.duration(30, 'minutes');

The startDate is 2019-11-02T11:57:00.701Z and the endDate is 2019-11-02T13:31:00.701Z

I need assistance in splitting this time range and returning the following result:

[
  {startDate: 2019-11-02T11:57:00.701Z, endDate: 2019-11-02T12:26:59.701Z}
  {startDate: 2019-11-02T12:27:00.701Z, endDate: 2019-11-02T12:56:59.701Z}
  {startDate: 2019-11-02T12:57:00.701Z, endDate: 2019-11-02T13:26:59.701Z}
  {startDate: 2019-11-02T13:27:00.701Z, endDate: 2019-11-02T13:31:00.701Z}
]

Answer №1

Utilizing the moment-range plugin

window['moment-range'].extendMoment(moment);

const start  = moment('2019-11-02T11:57:00.701Z');
const end    = moment('2019-11-02T13:31:00.701Z');
const range  = moment.range(start, end);

const rangeBy = range.by('minutes', { step: 30 });

const res = Array.from(rangeBy).map(m => ({
  'startTime': m.toISOString(),
  'endTime': m.add(29, 'm').add(59, 's').toISOString()
}))

if(moment(res[res.length -1].endTime).isAfter(end)) {
  res[res.length -1].endTime = end.toISOString();
}

console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.1/moment-range.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript to parse SOAP responses

Currently, I am working on a Meteor application that requires data consumption from both REST and SOAP APIs. The SOAP service is accessed using the soap package, which functions properly. However, I am facing challenges with the format of the returned data ...

Extract table information from MuiDataTable

I am having trouble retrieving the row data from MuiDataTable. When I try to set the index from the onRowSelectionChange function to a state, it causes my checkbox animation to stop working. Below is how my options are currently configured: const option ...

Having trouble retrieving documents from a nested collection in Firebase

I am attempting to retrieve all documents from Firebase that are based on a query. Here is my current firebase structure: https://i.stack.imgur.com/tXrX8.png Even though I have two documents inside the "ListaFavorite" collection, when I check using empty ...

Is there a specific type in typescript that represents every iterable object?

We have a unique function shown below: export const transformUndefinedToNull = (obj) => { const convert = (o) => { Object.keys(o).forEach((key) => { const value = o[key]; if (value === undefined) { o[key] = null; } ...

What is the best way to automatically post to Slack at regular intervals?

In order to provide users with the option to choose when they receive information from my API, such as daily at 5PM or every Friday at 5PM, I have a configuration page. Once users set their preferred time, I want to send them a Slack message at that specif ...

Tips for displaying autocomplete suggestions as clickable links?

I am new to using Ajax and trying to figure out how to display autocomplete results as clickable links. I have managed to list the related results, but I am struggling to add the links. I believe the links need to be added within the script as an HTML tag. ...

Should a React application perform a complete refresh when a file is reloaded?

Recently, I delved into the world of React and learned about one of its key benefits: updating only the necessary DOM elements. However, as I began building an app from scratch, I encountered a situation where every time I saved the .js file, it resulted ...

Securing important code sections in Node/Express using Typescript: A guide

I'm fairly new to the world of JavaScript/Typescript/Node/Express, and as I've been researching, it seems there isn't a universally accepted method for locking critical sections of code in a Node/Express application. I've come across a ...

Managing DOM elements within a Vue 3 template using Typescript

As I delve into the world of Vue 3 as a beginner, I encountered a challenge when it came to managing the DOM within Vue 3 templates. Let's take a look at the source code. MainContainer.vue <template> <div class="main-container" r ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...

React Table in Modal Using Custom Hook State

I'm facing some difficulties with the React useState hook. Currently, I have a modal that pops up after submitting a form. Before loading the modal, the application calls an API to fetch data, which is then displayed in a table within the modal. The ...

Limiting the displayed portion of a table and implementing scrolling instead

I am currently working with a static HTML template that contains the following code: <table> <thead></thead> <tbody></tbody> </table> Using jQuery and AJAX, I am dynamically adding and removing rows and columns ...

Collecting information from JSON files

Within the cells of my calendar are placeholders for events, dates, participants, and descriptions. Now, I am looking to populate these placeholders with data previously stored using localStorage. Unfortunately, my current code is not achieving this. How ...

Swapping values in JSON by comparing specific keys: A guide

I have JSON data that contains a key called reportData with an array of values: {"reportData":[ ["1185","R","4t","G","06","L","GT","04309","2546","2015","CF FE","01H1","20","23840","FF20"], ["1186","R","5t","R","01","L","TP","00110","1854","2016" ...

Ways to efficiently implement configuration settings in a functional approach

I've delved into the world of functional programming and I'm working on developing a package that needs to be configurable. My goal is to set up this configuration only once to maintain purity in my functions without relying on global state. Curr ...

Omit certain table columns when exporting to Excel using JavaScript

I am looking to export my HTML table data into Excel sheets. After conducting a thorough research, I was able to find a solution that works for me. However, I'm facing an issue with the presence of image fields in my table data which I want to exclude ...

After the page is reloaded, apply a class to the divs by selecting them based on the "data" attribute

I have a set of four cards labeled "card", each representing different body parts: eyes, torso, arms, and legs. <div class="card" data-lesson="eyes">eyes</div> <div class="card" data-lesson="torso">torso</div> <div class="card" ...

What is the best way to ensure that my $.ajax POST call works seamlessly with SSL?

Below is the JavaScript code I am using: parameter = "name=" + name + "&email=" + email + "&phone=" + phone + "&comments=" + comments; $.ajax({ url: 'sendEmail.php?' + parameter, success: ...

The "in operator" is not compatible with string indexes

Unique Code const example = { one: 'two', three: 'four', }; const keyToRetrieve: string = 'one'; if (keyToRetrieve in example) { console.log(example[keyToRetrieve]); // output: "two" (No Error) } Removing as const doe ...

Is there a method to accurately detect the rendering of individual elements within a React Component, rather than the entire component itself?

While it's known that Components rendering can be detected through React's Developer Tool, I came across other methods in this source. However, what I'm specifically interested in is detecting the rendering of individual elements within a Co ...