loading...
Cover image for Day counter with JavaScript

Day counter with JavaScript

walternascimentobarroso profile image Walter Nascimento ・2 min read

[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! 😊😊

Posted on by:

walternascimentobarroso profile

Walter Nascimento

@walternascimentobarroso

Software development | PHP | JavaScript | Database | Open-Source

Discussion

pic
Editor guide