DEV Community

Cover image for Day counter with JavaScript
Walter Nascimento
Walter Nascimento

Posted on

5

Day counter with JavaScript

[clique aqui para ler português]

Have you ever needed to know the difference in days between an end date and a start date? If so then we will create something simple to facilitate this counting of dates.

CODE

First we will create the interface, we will do something simple, using only HTML.

<h1>Calcular dias</h1>

<form name="form_main">
  <label for="date_ini">Date Inicial: </label> 
  <input name="date_ini" id="date_ini" type="date"> <br>
  <label for="date_end">Date Final: </label> 
  <input name="date_end" id="date_end" type="date"> <br>
  <label for="days">Dias passados: </label> 
  <span id="days"></span> <br>
  <button type="button" onclick="countDays()">Contar</button>
</form>

In the HTML structure, two inputs were created, one to receive the start date and the other with the end date.

Now let’s create the countDays() function.

const second = 1000;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;

function countDays() {
  let date_ini = new Date(document.form_main.date_ini.value);
  let date_end = new Date(document.form_main.date_end.value);

  let diff = date_end.getTime() - date_ini.getTime();

  document.getElementById('days').innerText = Math.floor(diff / day);
}

In this function (countDays()), the value of the start date and the end date is retrieved, and in the diff variable, the dates are subtracted and converted into a timestamp, after which a small calculation of the difference is made with the total of days.

ready as simple as that.

Demo

See the complete project working below.

Youtube

If you prefer to watch, I see the development on youtube (video in PT-BR).

Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you! 😊😊

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

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

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay