How to calculate the number of days between two dates using HTML, CSS, and javascript?
Welcome to today’s tutorial. Today we are going to create a webpage that will calculate the no. For this, we are going to use HTML, CSS and Javascript.
You need basic ES6 knowledge for this javascript project. This tutorial is well suited for javascript intermediates. Let us get started with the project.
Calculating the number of days between two dates in JavaScript required to use date object for any kind of calculation.
For that, first, get the internal millisecond value of the date using the in-built JavaScript getTime() function. As soon as both the dates get converted, proceed further by subtracting the later one from the earlier one which in turn returns the difference in milliseconds.
Later, the final result can be calculated by dividing the difference (which is in milliseconds) of both the dates by the number of milliseconds in one day.
LIVE SERVER:-
Before moving forward to the code first of all we will see the live sever of the code so you can see how it is working on clicking the button.
See the Pen Untitled by Himanshu Singh (@himanishu) on CodePen.
HTML:-
HTML is the basic layout of the website. I have used to income tax that is given ID input one and input 2 respectively and input type is Date.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="main">
<div class="input">
<div class="div">Enter the first date</div>
<input type="date" id="input1"></div>
<div class="input">
<div class="div">Enter the second date</div>
<input type="date" id="input2"></div>
<button id="btn" onClick="ans()">Click</button>
</div>
<div class="answer"></div>
</body>
</html>
CSS:-
body{
height:100vh;
width:100vw;
display:flex;
justify-content: center;
align-items: center;
flex-direction: column;
background:pink;
}
div{
padding:5px;
}
#btn{
align-self: center;
width:80px;
}
#main{
border:3px solid blue;
display: flex;
flex-direction:column;
}
JavaScript:-
var btn=document.getElementById("btn")
var input1=document.getElementById("input1")
var input2=document.getElementById("input2")
var answer=document.querySelector(".answer")
function ans(){
var Date1= new Date(input1.value)
var Date2= new Date(input2.value)
answer.innerHTML=`Difference between the 2 dates is ${(Date1-Date2)/(1000*60*60*24)} days.`
}
I hope hoped loved this blog and learnt many things at a place please let us know your review in the comment section if you liked it please comment below as it will give us motivation to create more blogs.