Unique: "Unique One-Step Deviation in Date Comparison"

A Little Background Information:

I am working with data points that span from the current day to 5 days ahead, in 3-hour intervals (such as 10pm, 1am, 4am, 7am...). My goal is to organize these data points into arrays sorted by date, with each array representing a single day.

Initially, I tried calculating the difference between the two date objects in terms of days by using the formula

(datapoint.getTime() - today.getTime())/ millisecondsPerDay
. However, this method did not work as intended, resulting in fractions of days.

Next, I attempted to round the results using Math.ceil() and Math.floor(), but this approach also failed because it grouped together the current day and parts of the following day (for example, 10pm + 3 hours is not on the same day, even though the difference is less than 1 day).

Then, I tried comparing the days using

let diff = tmp.getDate() - today.getDate()

However, this method presented challenges when transitioning between months. When approaching the end of the month and encountering datapoints from the next month, it produced relatively high negative values that could not be used as array indices (e.g. [0,1,2,4,5,-27]).

The Question:

How can I accurately calculate the difference between two dates in distinct day-steps while accounting for changes in months?

Answer №1

If your timestamps are given in milliseconds, you can try this method. First, divide both timestamps by (24 * 3600 * 1000) and round down using Math.floor() to get the number of complete days. Then, subtract the target date in days from the current date in days to find the difference.

For example,

mils_in_a_day = 24 * 3600 * 1000
today_in_days = Math.floor(today_in_mils / mils_in_a_day)
target_date_in_days = Math.floor(target_date_in_days / mils_in_a_day)
difference_in_days = target_date_in_days - today_in_days

To organize the results, you can create a hash for each example like this

results = {}
results[difference_in_days] = target_date_in_days

This will give you a hash structure with keys representing the difference in days and values as arrays of original timestamps. You can then use sort() on each array to sort timestamps within the same day.

While this approach may not be the most efficient, it should help you understand the concept.

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

Combine two pieces of data from a JSON object using Angular's ng-repeat

Trying to organize data from a separate array into one section of a table. The first JSON named "names" : [ { "name": "AAAAAA", "down": "False" }, { "name": "BBBBBB", "down": "Tru ...

The code within $(document).ready() isn't fully prepared

Feeling frustrated after spending hours searching and attempting to refactor one of my old modules on a rendered Mustache template. It's like diving into code chaos. <section id="slideShow"> <script id="slideShow-template" type="text/tem ...

Switch between Light and Dark Modes effortlessly with just one button

I've created a code that effortlessly switches between light mode and dark mode with the press of buttons. However, I'm looking to combine these two functionalities into a single toggle button for ease of use. If anyone can provide insight on how ...

Guide on utilizing automatic intellisense in a standard TextArea within a web application

I have successfully created an Online compiler web application that is currently running smoothly. However, I am now looking to enhance my application by implementing intellisense in the TextArea where the program is being typed. For instance, if I type "S ...

Is there a way to change a .pptx document into a base64 string?

Currently, I am working on a project that involves creating an addin for Office. The challenge I am facing is opening other pptx files from within the addin. After some research, I discovered that I need to use base64 for the PowerPoint.createPresentation( ...

Encountering the Firebase issue with error code (auth/invalid-api-key)

I keep encountering the error message 'Firebase: Error (auth/invalid-api-key) ' despite having entered all the correct authentication details. ...

Adjusting a parameter according to the width of the browser window?

Using Masonry, I have implemented code that adjusts the columnWidth to 320 when the screen or browser window width is less than 1035px. When the width exceeds 1035px, the columnWidth should be 240. However, the current code keeps the columnWidth at 320 re ...

What Is Preventing Fields from Being Filled in the Drop-Down Menu?

Looking to achieve this outcome: https://jsfiddle.net/nstruth/t0dopzav/1/ The issue I'm facing is that the HTML appears correctly when Volvo is selected, but the JavaScript is not functioning as expected. Despite reviewing similar innerHTML JavaScrip ...

The program encountered an error with code TS2339, indicating that the property "name" cannot be found on the type "never"

app.component.html I'm attempting to display the response data from my Firebase project using *ngFor. <div class="row"> <div class="col-md-3"> <h4 class="text-warning">All Employee Da ...

Transforming vertex coordinates of a polygon using Pixi.js

Greetings! I am a beginner in the world of pixijs (pixi.js - v5.2.4). I recently came across some intriguing examples on the official pixijs website. I decided to experiment by adding a simple slider. By adjusting the slider value, the position of a vertex ...

Twilio Fax Reception: Blank Body Detected

I have embarked on my journey with Twilio's Programmable Fax API and successfully followed their getting started guide. However, upon receiving the fax, I encounter an issue where the request body appears as an empty object when logged to the console. ...

What's the best way to constrain a draggable element within the boundaries of its parent using right and bottom values?

I am currently working on creating a draggable map. I have successfully limited the draggable child for the left and top sides, but I am struggling to do the same for the right and bottom sides. How can I restrict the movement of a draggable child based o ...

Unable to use global modules in NestJS without importing them

Currently, I am in the process of integrating a global module into my nest.js project I have written a service as shown below: export interface ConfigData { DB_NAME: string; } @Injectable() export class ConfigManager { private static _inst ...

Tips on serializing two arrays into JSON format and incorporating them in an AJAX request

I have a task where I need to retrieve all the names and details associated with a specific reference number. To accomplish this, I am using a while loop. However, I am unsure of how to encode these values in JSON format so that I can use them in AJAX for ...

Insufficient allocation - memory overflow in loopback.js

I encountered an issue while trying to fetch large data using loopback.js. The error message I received was: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory <--- Last few GCs ---> 45903 ms: Mark-sweep 1385.6 (14 ...

The duration from when the Ajax request is sent to when the response is received results in

Has anyone experienced strange results when measuring the time between sending and receiving an ajax request? Sometimes I get negative values. Can someone shed light on this peculiar behavior? var before = 0; var after = 0; $.ajax({ url: 'data.ph ...

Initiating Ajax to trigger the body's onLoad event

Whenever I use an ajax call to load a div, the entire page refreshes. It seems that the 'body onload=init()' event is triggered on ajax response causing all the initialization to repeat, which is not desired. Is there a way to only load the div t ...

Tips for Implementing a "Please Hold On" Progress Bar in ASP.NET

I have a master page named siteMaster.master, an aspx page called submission.aspx, and a user control named attachment.ascx. The script manager is included in my master page. The submission page inherits the master page and registers the user control attac ...

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' ...

Unable to modify page property status through the Notion API

I've been attempting to use the Notion JS-sdk to update a page's status using their API. However, I've run into some issues that I can't seem to resolve. Updating the status requires modifying the properties object, but no matter what ...