Calculate days between two dates in JavaScriptSometimes we need to calculate the number of days between two dates. This can be done using the JavaScript programming language. JavaScript provides a math function Math.floor() method to calculate the days between two dates. In JavaScript, we have to use the date object for any calculation to define the date using new Date(). To learn more about JavaScript in detail step by step follow our JavaScript tutorial. We will calculate the number of days in two ways:
We will discuss both the methods in detail with examples. Along with that, we will calculate the days remaining in Christmas day from today (date will be taken from the system).
Approach 1: Calculate the days by entering two datesThis approach will help to calculate the days between two dates by providing two different dates in code. Follow the below step:
Now, we will convert these steps into actual implementation. See the code below: Copy Code Test it NowOutput Number of days between dates Mon Jul 20 2015 00:00:00 GMT+0530 (India Standard Time) and Tue Sep 20 2016 00:00:00 GMT+0530 (India Standard Time) are: 502 days Screenshot Calculate days using dynamic HTML formIt is a dynamic JavaScript example in which a user can provide the input by itself on web instead of providing the dates input in code by the programmer. The user will dynamically choose the dates from the calendar and enter the two dates in input field and calculate the number of days between two dates by clicking on a button. See the code below: Copy Code Test it NowOutput Look at the screenshot below having two calendar input fields, one submit button to perform all the calculation and one more field to display calculated result. Approach 2: Calculate the days from current dateIn this approach, we will use the math function Math.floor() to calculate the days. Follow the below step:
Now, we will convert these steps into actual implementation. See the code below: Copy Code Test it NowOutput Number of days between dates Sun Sep 27 2020 19:42:13 GMT+0530 (India Standard Time) and Tue Dec 15 2021 21:45:10 GMT+0530 (India Standard Time) are: 444 days Screenshot Example 3: Calculate the days remaining in Christmas day from the current dateWe have one more example in which we will calculate the days till Christmas Day means for a specific date. Follow the below steps:
Now, convert these steps into actual implement to calculate the days remaining in Christmas. The implementation is as easy as the steps are. See the below code: Copy Code Test it NowOutput Number of days remaining in Christmas day: Mon Sep 28 2020 14:32:50 GMT+0530 (India Standard Time) and Fri Dec 25 2021 00:00:00 GMT+0530 (India Standard Time) are: 87 days Screenshot So, here was all the necessary examples (static and dynamic both) in JavaScript for calculating the days difference. To learn more about JavaScript in detail step by step follow our JavaScript tutorial.
Next TopicJavaScript String trim()
