JavaScript Differences Between Two Dates : Hi, welcome to the practice house. In this tutorial, we will learn about how to get the difference between two dates in JavaScript.

Almost all the time, we use date input field to select the date. Sometimes we need to find the difference between two dates. If you are stuck and don’t know how to do it. Don’t worry I got you covered.

HTML Part

We will create two date fields to select the date and one button to click and see what’s the Difference and another text field to show the difference.

<label for="fromDate">From Date :</label>
<input type="date" id="fromDate" name="fromDate">
<br/><br/>
<label for="toDate">To Date :</label>
<input type="date" id="toDate" name="toDate">
<br/><br/>
<button id="show">Show me the Different </button>
<br/><br/>
<label for="dateDiff">Date Different</label>
<input type="text" id="dateDiff" name="dateDiff">

HTML OUTPUT

htmloutput

How To Import jQuery Using CDN

We will use jQuery to calculate our date and we will find our difference between two dates.

In the HTML file please put this line into the head element. If you are not sure please download the source code from GitHub or check-in GitHub full source code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

JavaScript Part

Here is our javaScript code. It will work when we click our button. notice that for our button we have id is show. So we are using the .click function with our ID.

$("#show").click( function(){
let fromDate = $('input[name="fromDate"]').val();
console.log(fromDate);
let toDate = $('input[name="toDate"]').val();
console.log(toDate);
// Convert to Date
const date1 = new Date(fromDate);
const date2 = new Date(toDate);
let diff = 0;
if (date1 && date2) {
// ms per day = 1000 * 60 * 60 * 24 = 86400000
diff = Math.floor((date2.getTime() - date1.getTime()) / 86400000);
console.log(diff);
diff = diff + " days";
$('#dateDiff').val(diff);

Note that we are finding our Milliseconds per day using (1000 * 606024)

Output Sample 1:

Output Sample 2:

output sample 2 for how to get difference between two dates in javascript

Output Sample 3 :

Output Sample 3 To Count Past Days

Download Source Code :

Clone / Download the Sample Project from GitHub: Download / Clone Sample Project

Tagged:

Laisser un commentaire