Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - Age calculation

Tags:

javascript

Having 2 javascript Dates,

first is birthdate and second is a date to calculate age from that date.

What should be the best way to do this.

like image 222
user160820 Avatar asked Nov 02 '10 09:11

user160820


People also ask

How do I calculate age in HTML?

function calculateAge(date) { const now = new Date(); const diff = Math. abs(now - date ); const age = Math. floor(diff / (1000 * 60 * 60 * 24 * 365)); return age } var picker = new Pikaday({ field: document.

How to calculate age from date and time in JavaScript?

Calculate age using JavaScript. JavaScript offers some built-in date and time functions, which helps to calculate the age from the date (Date of Birth). Using these JavaScript methods, you can easily find the age of anyone. For this, we require a date input from the user and the current system date.

How to get the current age of a specific date?

A simple way to do this is using moment.js. We have two dates, the birth date (birthDate) and the other date used to calculate age from (specificDate). You can avoid this parameter and get the current age. moment(specificDate).diff(moment(birthDate), 'years');

How to calculate the age of the user using math?

Extract year from date using var year = age_dt.getUTCFullYear () Now calculate the age of the user using var age = Math.abs (year – 1970) Display the calculated age use document.write (“Age of the date entered: ” + age + ” years”); "Please type your full date of birth.";

How to create an age calculator using CSS?

Further, you can wrap these elements in div tags to style better. So, create the HTML for the age calculator as follows: <div class='indent-20'> <p> Enter your date of birth: <input id="dob" type="text" placeholder="dd/mm/yyyy"> (ex: dd/mm/YYYY) </p> <p> Your age: <span id="age"></span> </p> </div> Basic CSS Styles. The "indent-20" class


2 Answers

function calculateAge (birthDate, otherDate) {
    birthDate = new Date(birthDate);
    otherDate = new Date(otherDate);

    var years = (otherDate.getFullYear() - birthDate.getFullYear());

    if (otherDate.getMonth() < birthDate.getMonth() || 
        otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
        years--;
    }

    return years;
}

Example:

var age = calculateAge("02/24/1991", "02/24/2010"); // Format: MM/DD/YYYY
like image 199
Matt Avatar answered Oct 05 '22 02:10

Matt


Here is a way:

function getAge(d1, d2){
    d2 = d2 || new Date();
    var diff = d2.getTime() - d1.getTime();
    return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}
console.log( getAge(new Date(1978, 10, 3)) );

Be careful with the month. Javascript counts them from 0.
1978, 10, 3 means the November 3th, 1978

like image 20
Mic Avatar answered Oct 05 '22 01:10

Mic