-
-
Save fininhors/7d036b4a78a2c1a4368647ad8e3456c9 to your computer and use it in GitHub Desktop.
Função para calcular a idade de uma pessoa, tendo como base o dia de hoje
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Função CacularIdade | |
* Função para calcular a idade de uma pessoa, tendo como base o dia de hoje | |
* @params data - String referente à data de nascimento da pessoa, no formato dd/mm/yyyy | |
* @return Retorna uma string com a idade da pessoa em anos. | |
*/ | |
function calcularIdade(data) { | |
var now = new Date(); | |
var today = new Date(now.getYear(),now.getMonth(),now.getDate()); | |
var yearNow = now.getYear(); | |
var monthNow = now.getMonth(); | |
var dateNow = now.getDate(); | |
var dob = new Date(data.substring(6,10), | |
data.substring(3,5)-1, | |
data.substring(0,2) | |
); | |
var yearDob = dob.getYear(); | |
var monthDob = dob.getMonth(); | |
var dateDob = dob.getDate(); | |
var age = {}; | |
yearAge = yearNow - yearDob; | |
if (monthNow >= monthDob) | |
var monthAge = monthNow - monthDob; | |
else { | |
yearAge--; | |
var monthAge = 12 + monthNow -monthDob; | |
} | |
if (dateNow >= dateDob) | |
var dateAge = dateNow - dateDob; | |
else { | |
monthAge--; | |
var dateAge = 31 + dateNow - dateDob; | |
if (monthAge < 0) { | |
monthAge = 11; | |
yearAge--; | |
} | |
} | |
age = { | |
years: yearAge, | |
months: monthAge, | |
days: dateAge | |
}; | |
return age.years; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment