DEV Community

Cover image for How to Get Days Between two Dates in JavaScript
Shantanu Jana
Shantanu Jana

Posted on β€’ Edited on

8 2

How to Get Days Between two Dates in JavaScript

This tutorial will help you to know how to make Days Between two Dates calculator using JavaScript. Using this type of project you can calculate the time interval between two dates.

If you want to calculate how many days are left between two specific dates then you can use this get days between two dates javascript project.

βœ…βœ… Live Preview πŸ‘‰πŸ‘‰ Days Between Two Dates JavaScript

Here html's date input (type="date") is used. Which will help you to select the date. You can also input the date manually.

Here I have used HTML, CSS and JavaScript. After inputting the date, click on the submit button and you will see the time difference between the two dates.

Get Days Between two Dates in JavaScript

First a box was created on the web page. I first added a heading to the box. Then two input boxes were made for input. Input boxes were made. I have used the type date of the input box here.

This calculator will determine the interval between the two dates. Then who will turn that time into seconds. Then turn that time into day again. If you want, you can view this information as hours, minutes, seconds instead of days.

HTML Code:

I have added the necessary information of this Get Days Between two Dates calculator using the following html. First the basic structure was created.

Then the heading and input box. Then there is a submit button. At the end of all there is a display in which the calculated results can be seen.

<!--Basic structure of calculator-->
<div class="container">
 <!--Added a heading-->
   <div class="heading">Days Between Two Dates</div>
<!--Two input spaces-->
   <div class="inp-wrapper">
<!--Place to input 1st date-->
        <div class="date-wrapper">
          <label for="date-1">Start Date</label>
          <input type="date" id="date-1" />
        </div>
<!--Place to input 2nd date -->
        <div class="date-wrapper">
          <label for="date-2">End Date</label>
          <input type="date" id="date-2" />
        </div>
   </div>
<!-- Submit button -->
   <button id="submit">Submit</button>
<!-- Display -->
   <div id="output">Select the dates to get started</div>
    </div>
Enter fullscreen mode Exit fullscreen mode

CSS Code:

Now all the information has been designed by css. The background color of the webpage is blue and the background of the calculator is white.

/*Basic design of webpage*/
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: "Rubik", sans-serif;
}
body {
height: 100vh;
background: rgb(94, 169, 233);
}
/*Basic design of calculator*/
.container {
width: 70vw;
max-width: 37.5em;
background-color: #f6f9fa;
padding: 3em 1em;
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
}
/*Design the headings*/
.heading{
background: rgb(18, 128, 207);
color: white;
margin: -48px -16px 50px -16px;
font-size: 23px;
padding: 5px;
text-align: center;
}
/*Design a place to input*/
.inp-wrapper {
display: flex;
justify-content: space-around;
gap: 1.2em;
}
label {
color: #0f1e32;
display: block;
font-weight: 600;
}
input[type="date"] {
font-size: 16px;
padding: 1em;
color: #242831;
border: 2px solid rgb(7, 108, 147);
outline: none;
border-radius: 0.2em;
margin-top: 0.6em;
}
::-webkit-calendar-picker-indicator {
background-color: #7eceee;
padding: 0.2em;
cursor: pointer;
border-radius: 0.1em;
}
/*Design the Calculate button*/
button {
display: block;
background-color: #1a78db;
color: #ffffff;
font-size: 18px;
margin: 2.2em auto 2em auto;
border: none;
padding: 0.7em 2em;
border-radius: 0.3em;
font-weight: 500;
}
/*Display viewing results*/
#output {
background-color: rgba(255, 255, 255, 0.15);
text-align: center;
padding: 1em;
margin: 0px 30px 0px 30px;
color: #0a49c7;
font-size: 1.2em;
letter-spacing: 0.05em;
box-shadow: 0 0 20px rgba(0,139,253,0.45);
}
#output span {
color: #18f08b;
font-size: 1.4em;
font-weight: 600;
}
/*The following code has been used to make it responsive*/
@media screen and (max-width: 550px) {
.container {
  padding: 4em 2em;
}
.inp-wrapper {
  flex-direction: column;
}
.date-wrapper {
  display: flex;
  align-items: center;
  flex-direction: column;
}
}
Enter fullscreen mode Exit fullscreen mode

JavaScript:

Now is the time to activate this Get Number of Days Between Dates project using JavaScript. Of course, you need to have a basic idea about JavaScript.

   //The 'Submit Button' and 'Display' ids are set to constant
    let submit = document.getElementById("submit");
    let output = document.getElementById("output");

    submit.addEventListener("click", () => {
      //Create a Date object from input value
      let date1 = new Date(document.getElementById("date-1").value);
      let date2 = new Date(document.getElementById("date-2").value);

      //Check if the input dates are valid
      //If valid calculate the difference
      if (date1.getTime() && date2.getTime()) {
        //Calculate difference in time using getTime function
        //getTime calculates number of years since January 1,1970
        let timeDifference = date2.getTime() - date1.getTime();

        //Since this value is in milliseconds we need to convert it into days
        //We want the difference to be a non-negative number. Hence we use Math.abs()
        let dayDifference = Math.abs(timeDifference / (1000 * 3600 * 24));
//InnerHTML is a property of the HTML DOM.
        output.innerHTML = `Difference between the two dates is <span>${dayDifference}</span> days`;
      }

      //Else display that the input is valid
      else {
        output.innerHTML = "Please select a valid date";
      }
    });
Enter fullscreen mode Exit fullscreen mode

Hopefully you have been able to create this Get Days Between two Dates in JavaScript using the above code.

Related Post:

  1. Transparent Login Form
  2. Responsive Footer Design
  3. Simple Stopwatch using JavaScript
  4. Javascript Age Calculator
  5. Random Password Generator with JavaScript
  6. Preschool in Pune
  7. Sidebar Menu Using HTML CSS

If there is any problem, you can definitely comment. Use the link below for all the source code.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
amircahyadi profile image
Amir-cahyadi β€’

Useful but maybe must in codepen πŸ‘β€οΈ

Collapse
 
sehgalspandan profile image
Spandan Sehgal β€’

Amazing post.
Very useful
I calculated days between today and my bday
14 days left. yaaay :)
Keep it up!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay