Calculate Javascript Date Difference

Asked

Viewed 2,010 times

2

I’m learning Javascript and I’m making a retirement calculator. I would like to know how to take the two dates inserted in the html form and calculate the difference between them and output the difference.

I have the following html

<form name="aposentadoria">

<fieldset>
    <legend>Sexo</legend>
    <input type="radio" name="sexo" value="M" /><i class="fa fa-male"></i>Masculino:<br />
    <input type="radio" name="sexo" value="F" /><i class="fa fa-female"></i>Feminino<br />
</fieldset>

<select name="regra">
    <option value="25">25 anos</option>
    <option value="20">20 anos</option>
    <option value="15">15 anos</option>
</select>

<label for="empresa">Empresa</label>
    <input type="text" name="empresa" placeholder="Empresa: ">

<label for="dataAdm">Admissão</label>
    <input type="date" name="dataAdmissao" placeholder="Admissão: ">

<label for="dataDem">Demissão</label>
    <input type="date" name="dataDemissao" placeholder="Demissão: ">
<input type="button" value="Calcular" onclick="calcula()" >

And Javascript

function calcula(){
var sexo = document.aposentadoria.sexo.value;
var regra = document.aposentadoria.regra.value;
var empresa = document.aposentadoria.empresa.value;
var dataAdmissao = document.aposentadoria.dataAdmissao.value;
var dataDemissao = document.aposentadoria.dataDemissao.value;
var anosAjus = "Você trabalhou " + "anos nas empresas " +empresa+ " sob a regra de " +regra;

alert(anosAjus);
}

Could you help me with this calculation?

1 answer

2


You have to convert these input values into a date object and then compare them. How do I think you only want to compare the years, you can do it like this:

var dataAdmissao = new Date(document.aposentadoria.dataAdmissao.value);
var dataDemissao = new Date(document.aposentadoria.dataDemissao.value);
var anosAjus = dataDemissao.getFullYear() - dataAdmissao.getFullYear();

Depending on the level of detail you need you can take into account if the start date is the end of the service they complete 12 months between them to count or not the last year, count with the holidays etc. You can also simply use timestamp (milliseconds) and look for the difference between the two dates so: anosAjus / 86400000 / 365 which is a rough approach without taking into account leap years.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.