How to get Difference between two Dates in days using jQuery ?
In this article, we will learn how to find the difference between the 2 dates in days using jQuery. Here, we will take the input for the dates using a jquery datepicker.
Considering the given below 2 input Dates, we need to calculate the difference between them which will be returned in a number of days.
Input : 02/17/2022 02/10/2022 Output: 7
For this, we will use some functions such as the getTime() method, Date() in the code. We will discuss both methods sequentially.
getTime(): It returns the number of milliseconds since January 1, 1970 00:00:00. This method does not accept any arguments.
Date(): The Date objects are created with the new Date() constructor. All the arguments passed to the Date() are optional.
new Date(year, month, day, hours, minutes, seconds, milliseconds)
jQuery Date Picker: A date-picker of jQuery UI is used to provide a calendar for the user to select the date from a Calendar.
$( selector ).datepicker();
- Take two dates as input using datepicker.
- Now, convert them into date types using the Date() method.
- By using getTime() on both dates, we will get the number of milliseconds since January 1, 1970 00:00:00.
- Calculate the absolute difference between the milliseconds of two dates.
- Convert the milliseconds to days by using the following formula
days = milliseconds / (1000 * 36000 * 24)
Example: This example illustrates getting the difference between 2 dates in days using jQuery.
Please Login to comment...