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?