Input type="date"

0

I need to get the value corresponding to the year of a <input type="date"> and subtract from the current date, to display the age of a user (javascript). However, my result always gives "NaN". How do I solve it? And how do I get JS itself to fetch the date (such as PHP's date("Y") fault)?

var data = parseInt($('input[id=nasc]').val());
var ano = 2017;
var idade = ano - data;
localStorage.setItem("diaNasc", idade);
    
asked by anonymous 08.05.2017 / 00:50

1 answer

1

To work with date in and convert a date of input of type="date" use new Date of title=" show questions tagged 'javascript' "> javascript where:

var dataAtual = new Date(); // retornar a data atual (Date)

and

var dataInput = new Date($("#nasc").val()); // converte o valor para Date

Then just do the subtraction operation using the getFullYear () method. :

var diferenca = dataAtual.getFullYear() - dataInput.getFullYear();

Full Code:

$("#nasc").on('blur', function() {
  calcular_idade();
});

function calcular_idade() {
  if ($('#nasc').val() != '') {
    var dataInput = new Date($("#nasc").val());
    if (!isNaN(dataInput)) {
      var dataAtual = new Date();
      var diferenca = dataAtual.getFullYear() -
                      dataInput.getFullYear();
      $("#lblidade").html(diferenca);
      return true;
    }
  }
  $("#lblidade").html('Data inválida');
  return false;  
}

calcular_idade();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="date" name="nasc" id="nasc" value="1980-10-01" />
<label id="lblidade"></label>

08.05.2017 / 02:27