Date manipulation and calculations are core to a huge amount of enterprise business logic. Being a wizard at using dates and turning them into simple values to run your logic on is critical. Knowing how to calculate the number of days between two dates is an essential piece of logic to have in your utility belt. This post will explain clearly how the math works as well as creating a simple utility function that can be used anywhere.
The key with the below code snippet is that subtracting one date from another will automatically convert the date objects into their base millisecond form to perform the arithmetic.
We can then divide the millisecond subtraction by the number of milliseconds in one day to factor the number down to days.
Using Math.abs to enforce the absolute value of the above calculation will ensure the number of days calculated is a positive number.
If you liked this post, please share it!