2012-04-04 13 views
8

Eventuali duplicati:
Calculate age in JavaScriptOttenere età da nascita

In un certo punto del mio codice JS ho jquery data di oggetto che è di una persona data di nascita. Voglio calcolare l'età della persona in base alla sua data di nascita.

Qualcuno può dare codice di esempio su come ottenere questo.

+2

downvoted, come è [facilmente ricercabili] (https://duckduckgo.com/?q=get%20age%20from%20birth%20date%20javascript). Non riesco a pensare a come hai ottenuto quell'invallo! – halfer

risposta

38

Prova questa funzione ...

function calculate_age(birth_month,birth_day,birth_year) 
{ 
    today_date = new Date(); 
    today_year = today_date.getFullYear(); 
    today_month = today_date.getMonth(); 
    today_day = today_date.getDate(); 
    age = today_year - birth_year; 

    if (today_month < (birth_month - 1)) 
    { 
     age--; 
    } 
    if (((birth_month - 1) == today_month) && (today_day < birth_day)) 
    { 
     age--; 
    } 
    return age; 
} 

O

function getAge(dateString) 
{ 
    var today = new Date(); 
    var birthDate = new Date(dateString); 
    var age = today.getFullYear() - birthDate.getFullYear(); 
    var m = today.getMonth() - birthDate.getMonth(); 
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) 
    { 
     age--; 
    } 
    return age; 
} 

See Demo.

+1

Molto bello! Visto che hai solo un comando in if (age--;), le parentesi sono facoltative, ma comunque piuttosto buone. Combinerei anche tutte le dichiarazioni var in una divisione con virgole, ma nel complesso, ottimo codice, molto utile. Grazie compagno! – davewoodhall

+0

Ho provato la demo e dato la data di nascita il 01 giugno 1998 (oggi è il 2 novembre 2016). Ciò significa che la persona di 18 anni ora. Ma mostra un messaggio di errore che Età dovrebbe essere maggiore o uguale a 18. Non preciso quindi votare verso il basso. – Syed

+0

codice molto utile –

20

JsFiddle

È possibile calcolare con le date.

var birthdate = new Date("1990/1/1"); 
var cur = new Date(); 
var diff = cur-birthdate; // This is the difference in milliseconds 
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25 
+0

Penso che ti sia dimenticato di moltiplicare per 24 nell'ultima riga –

+0

Hehe * doh *. Tuttavia JsFiddle aveva ragione. Grazie –

+4

Probabilmente è meglio dividere per 1000 * 60 * 60 * 24 * 365.25 –

4
function getAge(birthday) { 
    var today = new Date(); 
    var thisYear = 0; 
    if (today.getMonth() < birthday.getMonth()) { 
     thisYear = 1; 
    } else if ((today.getMonth() == birthday.getMonth()) && today.getDate() < birthday.getDate()) { 
     thisYear = 1; 
    } 
    var age = today.getFullYear() - birthday.getFullYear() - thisYear; 
    return age; 
} 

JSFiddle

+0

Più preciso di quello sopra indicato come risposta. Grazie!! – Syed

Problemi correlati