Calculate difference between dates in JavaScript

2

I'm learning Javascript and I'm making a retirement calculator. I would like to know how to get the two dates entered in the html form and calculate the difference between them and give the difference as output.

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?

    
asked by anonymous 02.04.2016 / 18:35

1 answer

2

You need to convert these input values to a data object and then compare them. As it seems that you only want to compare the years, you can do so :

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 whether the start date is the end of the service, or 12 months between them to count the last year or not, count on vacations etc. You can also simply use timestamp (milliseconds) and look for the difference between the two dates like: anosAjus / 86400000 / 365 which is a rough approximation without taking leap years into account.

    
02.04.2016 / 19:46