Calculating minutes per hour during a specific date range using JavaScript

What is the method to create an array representing minute counts per hour within a specified date range?

If we have the following dates:

const initial = new Date('2019-04-04 12:14');
const final = new Date('2019-04-04 16:21');

How can we transform this into an array structured like the example below:

const minutes_per_hour = [
    {
        hour: 12,
        minute_count: 46
    },
    {
        hour: 13,
        minute_count: 60
    },
    {
        hour: 14,
        minute_count: 60
    },
    {
        hour: 15,
        minute_count: 60
    },
    {
        hour: 16,
        minute_count: 21
    }
];

Answer №1

Below is a straightforward function that accomplishes the task you're looking for. It operates by continuously calculating the minutes until the following hour (or end, if it's closer) and advancing to the next hour, ceasing when end is reached.

/**
 * This function retrieves the number of minutes in each consecutive hour within a specified time range
 * @param {Date} start
 * @param {Date} end
 * @return {{hour:number, minute_count:number}[]}
 */
function getMinutesPerHour(start, end) {
  const output = [];
  let current = start;
  while (current < end) {
    const minutesUntilNextHour = 60 - current.getMinutes();
    const nextHour = new Date(+current + minutesUntilNextHour * 60 * 1000);
    const minutes = nextHour > end
      ? end.getMinutes() - current.getMinutes()
      : minutesUntilNextHour;
    output.push({ hour: current.getHours(), minutes: minutes, });
    current = nextHour;
  }
  return output;
}

console.log(getMinutesPerHour(new Date('2019-04-04 12:14'), new Date('2019-04-04 16:21')));

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

Oops! Module './api/routers' not found

Hello, I hope everyone is doing well... Currently, I am working on developing a NextJS single-page web application. To create a custom server for NextJs, I am utilizing Express, MongoDB, and nodemon for hot reload functionality. Upon starting the server, ...

Upon selecting the correct prompt, it fails to respond when I press enter

I attempted to use a multi-search script that I found on a website. I followed the instructions given and made the necessary changes. After saving the file as an HTML document, I opened it in Chrome. However, when I type in a word and hit enter, nothing ha ...

Tips for updating an element in an array by using another element from a separate array

What is the objective? We have two arrays: orders and NewOrders We need to check for any orders with the same order_id in both arrays. If there is a match, we then compare the order status. If the order from the NewOrders array has a different status, w ...

Stop receiving updates from an Observable generated by the of method

After I finish creating an observable, I make sure to unsubscribe from it immediately. const data$ = this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1').subscribe(res => { console.log('live', res); data$.unsubscr ...

Synchronous execution in Node.js: Best practices for coordinating tasks

While Node.js is known for its asynchronous nature, I am seeking to perform tasks in a sequential manner as outlined below: 1. Make an API request > 2. Convert the body from XML to JSON.stringify format > 3. Pass the string to a template. request.g ...

Configuring headless unit testing with requirejs

Seeking a JavaScript unit testing environment, I feel like I'm on a quest for the Holy Grail. The criteria are as follows: testing Requirejs AMD modules isolating each module by mocking out dependencies ability to test in-browser during development ...

When transferring JavaScript Array via Ajax to PHP, it results in a null response

I am attempting to send a JavaScript array to PHP, but the post data keeps returning null. Here is my JavaScript code: console.log($Seats); console.log($Seats.toString()); console.log(JSON.stringify({ $Seats })); var jsonStr = JSON.stringify($Seats); $.a ...

How to access webpack's require.context feature on the development server

In my webpack development configuration, I have set up a mocked backend using Express. Following an example from the DevServer Docs, my setup looks something like this: module.exports = { // ... devServer: { setupMiddlewares: (middlewares, devServe ...

Methods for transferring data to controller in Angular Modal service

After implementing the angular modal service discussed in this article: app.service('modalService', ['$modal', function ($modal) { var modalDefaults = { backdrop: true, keyboard: true, m ...

Populate the table with JSON content using jQuery

I am attempting to populate a table with JSON data using jQuery, but the content within the div remains empty. I need assistance in identifying the error. The array list contains the data (I verified this using console.log(list)). Additionally, list[' ...

Requesting information asynchronously returns a positive response

I wrote the following code: if (venue_exists(instagramUserID)){ alert('A'); }else { alert('C'); } function venue_exists(instagramUserID) { $.get( "/venues/" + instagramUserID, function( ...

AngularJS - Not binding $scope to the DOM

Recently starting out with Angular, I decided to practice by creating a simple website. One of the features I want to include is displaying the number of times a button has been clicked through data binding. Here's the controller code I've writte ...

Developing a tool for switching between languages in an internationalization application

I have been exploring the implementation of Lingui(i18n) in apps. All set up, but I'm interested in adding a language switcher to enable users to change between language catalogs on my app. Here's my index.js file: import React, { useEffect } fr ...

Can ngFor be utilized within select elements in Angular?

I'm facing an interesting challenge where I need to display multiple select tags with multiple options each, resulting in a data structure that consists of an array of arrays of objects. <div class="form-group row" *ngIf="myData"> <selec ...

Get the ID from a row that was created dynamically

I have a webpage that pulls information from my database and displays it. Users should be able to click on the "details" link to see more details about a particular record, or click on an input box in the "check" column and submit to update the record stat ...

Tips for ensuring an HTML element remains within defined boundaries

Currently working on a visualization tool for search algorithms using React, I've encountered a minor issue when moving the start or end nodes. Upon clicking and dragging the mouse across the grid, the nodes adjust accordingly until reaching the grid& ...

Unable to successfully download npm packages - encountered an error running `[email protected] install: `node-pre-gyp install --fallback-to-build` on Ubuntu 18.04 system

I am facing an issue while trying to npm install (using lerna bootstrap) a project on Ubuntu 18.04. The error I encounter is related to node-pre-gyp install --fallback-to-build. I have attempted installing node-gyp, node-pre-gyp, and apt-get build-essenti ...

Breaking down csv column into multiple subcolumns using numpy data type and conversion methods

Currently, I have a csv file that contains various columns with measured values along with their error values. My goal is to import this data into Python using numpy's genfromtxt and format the array using dtype. Suppose the csv file is structured lik ...

Tips for connecting a Django API project with a nodejs and react frontend

I'm currently working on a Django API project and I am considering incorporating Node.js into the mix. Additionally, I am interested in using React for the frontend of the application. Is this combination of technologies feasible? Would it be advisabl ...

Node JS: Despite modifying the URL, the response remains unchanged

My attempt to log in to teeSpring.com and retrieve a response from another URL using a login cookie seems to be causing an issue. Upon logging into teeSpring.com, the dashboard details are returned. However, when I try to make a GET request to the second U ...