Calculating every number within a range of dates and storing them in the format of [day, hour]

Given two date pairs represented as numbers [hour, weekday], where hour ranges from 0-23 and weekday ranges from 1-7. I am tasked with generating all the hours in between each pair. For example, if given [13, 2] and [2, 3], the output would be:

[13,2]
[14,2]
[15,2]
...
[0,3]
[1,3]
[2,3]

I also have the dates stored as datetimes, but I'm unsure which representation to utilize for the task at hand. The time interval between the two dates is always just a few days and does not span across weeks.

Answer №1

If you create a function called next for determining the next date by using the modulo operator % to choose the upcoming hour and day, you can then use a basic while loop to generate all dates within a specified range:

function next([hour, day]) {
  let nextHour = (hour + 1) % 24;
  let nextDay = nextHour === 0 ? (day % 7) + 1 : day;
  return [nextHour, nextDay];
}

function range([h1, d1], [h2, d2]) {
  let res = [], ch = h1, cd = d1;
  while (ch !== h2 || cd !== d2) {
    res.push([ch, cd]);
    [ch, cd] = next([ch, cd]);
  }
  res.push([ch, cd]);
  return res;
}

console.log(range([13, 2], [2, 3]));
console.log(range([13, 7], [10, 2]));

Answer №2

To simplify the process, consider utilizing two Date objects instead. A potential implementation could look like this:

var start = new Date(2018, 11, 20, 13);
var end = new Date(2018, 11, 21, 3);
var timeRange = [];


while(start.getTime() <= end.getTime()) {
   timeRange.push(new Date(start.getTime()))
   start.setHours(start.getHours() + 1);
}

console.log(timeRange)

Answer №3

If you want to achieve something similar, consider the following approach:

const getNewDate = (hour, day) => {
  let currentDate = new Date()
  currentDate.setHours(hour)
  currentDate.setDate(currentDate.getDate() - currentDate.getDay() + day);
  return currentDate
}
const createRange = (start, end) => {
  let [startingHour, startingDay] = start, [endingHour, endingDay] = end, result = []
  const firstDate = getNewDate(startingHour, startingDay), lastDate = getNewDate(endingHour, endingDay)

  while (firstDate < lastDate) {
    firstDate.setHours(firstDate.getHours() + 1)
    result.push([firstDate.getHours(), firstDate.getDay()])
  }
  return result
}

console.log(createRange([13, 2], [2, 3]))
console.log(createRange([11, 1], [3, 2]))

The concept involves creating two different dates and then continuously adding hours in a while loop until the start date surpasses the end date.

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

An anchor-shaped name tag with a touch of flair

I stumbled upon this unique anchor name design on the website Does anyone here know how to create something similar? What is that style called? ...

Experiencing issues while attempting basic private key encryption with the Node crypto library

Currently, I am in the process of creating a quick proof of concept (POC) to encrypt an incoming string using a standard key. Below is the code snippet from my middleware: import Crypto from 'crypto'; export default async function encrypt(req, r ...

Manipulating Images with jQuery: Adding and Removing Images Without Affecting Text

Below is the code I'm working with: <input type = checkbox id = "purple" name = "box" > Purple </input> <div id = birdcage></div> This is the JavaScript section: $("#purple").click(function(){ if ($("#purple").is(":chec ...

What is the best way to add attachments to the clipboard in a Chrome extension?

One possible way to achieve this is by using the navigator.clipboard.write API, but keep in mind that this API is not available to background pages of Chrome extensions. A method I attempted involved creating a blob like this: let blobFinal = null; // ...

What causes the consistent filling of responses in jQuery ajax?

After observing that the response of an ajax call using jQuery is never empty, I have come across the following code snippet: $.ajax({ type: "get", data: { data }, url: "phpFile", datatype: 'text' }).done(functio ...

Navigating through different components in React is made possible with React Router

I have views in my application that depend on each other. For example, in one view a user can choose an item from a list (generated on the server), and in the next view they can perform operations on that selected item. The item is passed to the second v ...

Selenium Python Slider Button Element Visibility Issue

Currently, I am developing a parser to automate the process of clicking buttons on a website. However, I am encountering difficulties in clicking two specific buttons. The buttons I am aiming to click are "Elija el imports a financiar" and "Elija la mensu ...

Error: Unable to assign value to property 'src' because it is null

Currently, I am attempting to display a .docx file preview using react-file-viewer <FileViewer fileType={'docx'} filePath={this.state.file} //the path of the url data is stored in this.state.file id="output-frame-id" ...

Encountering the React Native error message "TypeError: Object(...) is not a function" while using react navigation stack

I am currently facing an issue with my react-navigation-stack. My suspicion lies in the dependencies, but I am uncertain whether that is the root cause. The objective at hand is to create a text redirecting to another page. If there is any irrelevant code, ...

Show the text from the chosen option using jQuery with a button

Hey everyone, I have a question regarding a coding issue I'm facing. In this problem, I am unable to display the text from the selected option when I click the order button. The desired result is to show the selected option that I choose and display i ...

Can someone explain the crazy math used in three.js?

I've recently started learning three.js, and I keep encountering these complex mathematical formulas that seem confusing. Take this example for instance: mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeig ...

Adding JavaScript files to a project in Ionic2 with Angular2 integration

I'm looking to incorporate jQuery into my Ionic2 app, which requires loading several JavaScript files: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/j ...

Refreshing the access token in Linkedin's oauth does not result in extending the expiration time

Currently, I am implementing a strategy to renew Linkedin OAuth2 access tokens. When starting the OAuth process in the browser, the dialogue is skipped and a new code is generated. This code is then used to acquire a fresh access_token that differs from t ...

How to efficiently remove duplicate items from multiple select dropdowns in Angular using ng-repeat?

Need help with dynamically assigning objects to select boxes in AngularJS. I have a scenario where I add multiple select boxes to a form, but each box should only display items that haven't been selected in other boxes. How can I achieve this functio ...

Using Jquery to send json data to a webserver via Ajax (API)

Currently, I am attempting to use AJAX to post data to a JSON file (API) on a server. As part of this process, I have implemented dragging functionality for two Kineticjs shapes on the stage. Upon stopping the drag action, my goal is to save the updated x ...

Refresh Angular controller after ng-click event is triggered

In my current setup, I have a controller that consists of one main object containing various functions. Initially, default values for variables are set and the init() function is used to fetch data from the database. Everything on the page seems to be fu ...

Sending Parsed Information to Callback for Flexible Use

Is there a way to pass the value of coins, or even better, currency to my callback function so I can freely use the parsed JSON data in other functions? function fetchJSON(path, callback) { var jsonReq = new XMLHttpRequest(); jsonReq.onreadystatechang ...

Attempting to call a nested div class in JavaScript, but experiencing issues with the updated code when implemented in

Seeking assistance. In the process of creating a nested div inside body > div > div . You can find more information in this Stack Overflow thread. Check out my JSFiddle demo here: https://jsfiddle.net/41w8gjec/6/. You can also view the nested div ...

Issue: requireJS configuration is invalid

Here is the file structure of my project - src |- main.js |- math.js The math.js file acts as an AMD module and is being required in main.js. I have npm installed require.js and included it in main.js. //main.js var rjs = require('requirejs' ...

Filtering rows in JQgrid is made easy after the addition of a new record

Here's the situation I'm facing: Every second, my script adds a new record using the "setInterval" function: $("#grid").jqGrid('addRowData', id, data, 'first').trigger("reloadGrid"); However, when users apply filters while t ...