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.
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.
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.
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');
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.";
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With