Javascript Age count from Date of Birth - javascript

I'm passing my calendar selected date of birth to following JS function for calculating Age:
var DOBmdy = date.split("-");
Bdate = new Date(DOBmdy[2],DOBmdy[0]-1,DOBmdy[1]);
BDateArr = (''+Bdate).split(' ');
//document.getElementById('DOW').value = BDateArr[0];
Cdate = new Date;
CDateArr = (''+Cdate).split(" ");
Age = CDateArr[3] - BDateArr[3];
Now, lets say, input age is: 2nd Aug 1983 and age count comes: 28, while as August month has not been passed yet, i want to show the current age of 27 and not 28
Any idea, how can i write that logic, to count age 27 perfectly with my JS function.
Thanks !

Let birth date be august 2nd 1983, then the difference in milliseconds between now an that date is:
var diff = new Date - new Date('1983-08-02');
The difference in days is (1 second = 1000 ms, 1 hour = 60*60 seconds, 1 day = 24 * 1 hour)
var diffdays = diff / 1000 / (60 * 60 * 24);
The difference in years (so, the age) becomes (.25 to account for leapyears):
var age = Math.floor(diffdays / 365.25);
Now try it with
diff = new Date('2011-08-01') - new Date('1983-08-02'); //=> 27
diff = new Date('2011-08-02') - new Date('1983-08-02'); //=> 28
diff = new Date('2012-08-02') - new Date('1983-08-02'); //=> 29
So, your javascript could be rewritten as:
var Bdate = new Date(date.split("-").reverse().join('-')),
age = Math.floor( ( (Cdate - Bdate) / 1000 / (60 * 60 * 24) ) / 365.25 );
[edit] Didn't pay enough attention. date.split('-') gives the array [dd,mm,yyyy], so reversing it results in[yyyy,mm,dd]. Now joining that again using '-', the result is the string 'yyyy-mm-dd', which is valid input for a new Date.

(new Date() - new Date('08-02-1983')) / 1000 / 60 / 60 / 24 / 365.25
That will get you the difference in years, you will occasionally run into off-by-one-day issues using this.

May be this works:
var today = new Date();
var d = document.getElementById("dob").value;
if (!/\d{4}\-\d{2}\-\d{2}/.test(d)) { // check valid format
return false;
}
d = d.split("-");
var byr = parseInt(d[0]);
var nowyear = today.getFullYear();
if (byr >= nowyear || byr < 1900) { // check valid year
return false;
}
var bmth = parseInt(d[1],10)-1;
if (bmth<0 || bmth>11) { // check valid month 0-11
return false;
}
var bdy = parseInt(d[2],10);
if (bdy<1 || bdy>31) { // check valid date according to month
return false;
}
var age = nowyear - byr;
var nowmonth = today.getMonth();
var nowday = today.getDate();
if (bmth > nowmonth) {age = age - 1} // next birthday not yet reached
else if (bmth == nowmonth && nowday < bdy) {age = age - 1}
alert('You are ' + age + ' years old');

I just had to write a function to do this and thought'd I'd share.
This is accurate from a human point of view! None of that crazy 365.2425 stuff.
var ageCheck = function(yy, mm, dd) {
// validate input
yy = parseInt(yy,10);
mm = parseInt(mm,10);
dd = parseInt(dd,10);
if(isNaN(dd) || isNaN(mm) || isNaN(yy)) { return 0; }
if((dd < 1 || dd > 31) || (mm < 1 || mm > 12)) { return 0; }
// change human inputted month to javascript equivalent
mm = mm - 1;
// get today's date
var today = new Date();
var t_dd = today.getDate();
var t_mm = today.getMonth();
var t_yy = today.getFullYear();
// We are using last two digits, so make a guess of the century
if(yy == 0) { yy = "00"; }
else if(yy < 9) { yy = "0"+yy; }
yy = (today.getFullYear() < "20"+yy ? "19"+yy : "20"+yy);
// Work out the age!
var age = t_yy - yy - 1; // Starting point
if( mm < t_mm ) { age++;} // If it's past their birth month
if( mm == t_mm && dd <= t_dd) { age++; } // If it's past their birth day
return age;
}

Related

How to calculate automatically number of days between two dates in javascript? [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 3 months ago.
I want to calculate date difference in days, hours, minutes, seconds, milliseconds, nanoseconds. How can I do it?
Assuming you have two Date objects, you can just subtract them to get the difference in milliseconds:
var difference = date2 - date1;
From there, you can use simple arithmetic to derive the other values.
var DateDiff = {
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return Math.floor((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
},
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
var dString = "May, 20, 1984";
var d1 = new Date(dString);
var d2 = new Date();
document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2));
document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2));
document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2));
document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2));
Code sample taken from here.
Another solution is convert difference to a new Date object and get that date's year(diff from 1970), month, day etc.
var date1 = new Date(2010, 6, 17);
var date2 = new Date(2013, 12, 18);
var diff = new Date(date2.getTime() - date1.getTime());
// diff is: Thu Jul 05 1973 04:00:00 GMT+0300 (EEST)
console.log(diff.getUTCFullYear() - 1970); // Gives difference as year
// 3
console.log(diff.getUTCMonth()); // Gives month count of difference
// 6
console.log(diff.getUTCDate() - 1); // Gives day count of difference
// 4
So difference is like "3 years and 6 months and 4 days". If you want to take difference in a human readable style, that can help you.
Expressions like "difference in days" are never as simple as they seem. If you have the following dates:
d1: 2011-10-15 23:59:00
d1: 2011-10-16 00:01:00
the difference in time is 2 minutes, should the "difference in days" be 1 or 0? Similar issues arise for any expression of the difference in months, years or whatever since years, months and days are of different lengths and different times (e.g. the day that daylight saving starts is 1 hour shorter than usual and two hours shorter than the day that it ends).
Here is a function for a difference in days that ignores the time, i.e. for the above dates it returns 1.
/*
Get the number of days between two dates - not inclusive.
"between" does not include the start date, so days
between Thursday and Friday is one, Thursday to Saturday
is two, and so on. Between Friday and the following Friday is 7.
e.g. getDaysBetweenDates( 22-Jul-2011, 29-jul-2011) => 7.
If want inclusive dates (e.g. leave from 1/1/2011 to 30/1/2011),
use date prior to start date (i.e. 31/12/2010 to 30/1/2011).
Only calculates whole days.
Assumes d0 <= d1
*/
function getDaysBetweenDates(d0, d1) {
var msPerDay = 8.64e7;
// Copy dates so don't mess them up
var x0 = new Date(d0);
var x1 = new Date(d1);
// Set to noon - avoid DST errors
x0.setHours(12,0,0);
x1.setHours(12,0,0);
// Round to remove daylight saving errors
return Math.round( (x1 - x0) / msPerDay );
}
This can be more concise:
/* Return number of days between d0 and d1.
** Returns positive if d0 < d1, otherwise negative.
**
** e.g. between 2000-02-28 and 2001-02-28 there are 366 days
** between 2015-12-28 and 2015-12-29 there is 1 day
** between 2015-12-28 23:59:59 and 2015-12-29 00:00:01 there is 1 day
** between 2015-12-28 00:00:01 and 2015-12-28 23:59:59 there are 0 days
**
** #param {Date} d0 - start date
** #param {Date} d1 - end date
** #returns {number} - whole number of days between d0 and d1
**
*/
function daysDifference(d0, d1) {
var diff = new Date(+d1).setHours(12) - new Date(+d0).setHours(12);
return Math.round(diff/8.64e7);
}
// Simple formatter
function formatDate(date){
return [date.getFullYear(),('0'+(date.getMonth()+1)).slice(-2),('0'+date.getDate()).slice(-2)].join('-');
}
// Examples
[[new Date(2000,1,28), new Date(2001,1,28)], // Leap year
[new Date(2001,1,28), new Date(2002,1,28)], // Not leap year
[new Date(2017,0,1), new Date(2017,1,1)]
].forEach(function(dates) {
document.write('From ' + formatDate(dates[0]) + ' to ' + formatDate(dates[1]) +
' is ' + daysDifference(dates[0],dates[1]) + ' days<br>');
});
<html lang="en">
<head>
<script>
function getDateDiff(time1, time2) {
var str1= time1.split('/');
var str2= time2.split('/');
// yyyy , mm , dd
var t1 = new Date(str1[2], str1[0]-1, str1[1]);
var t2 = new Date(str2[2], str2[0]-1, str2[1]);
var diffMS = t1 - t2;
console.log(diffMS + ' ms');
var diffS = diffMS / 1000;
console.log(diffS + ' ');
var diffM = diffS / 60;
console.log(diffM + ' minutes');
var diffH = diffM / 60;
console.log(diffH + ' hours');
var diffD = diffH / 24;
console.log(diffD + ' days');
alert(diffD);
}
//alert(getDateDiff('10/18/2013','10/14/2013'));
</script>
</head>
<body>
<input type="button"
onclick="getDateDiff('10/18/2013','10/14/2013')"
value="clickHere()" />
</body>
</html>
use Moment.js for all your JavaScript related date-time calculation
Answer to your question is:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
Complete details can be found here
adding to #paresh mayani 's answer, to work like Facebook - showing how much time has passed in sec/min/hours/weeks/months/years
var DateDiff = {
inSeconds: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/1000);
},
inMinutes: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/60000);
},
inHours: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/3600000);
},
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
},
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
var dString = "May, 20, 1984"; //will also get (Y-m-d H:i:s)
var d1 = new Date(dString);
var d2 = new Date();
var timeLaps = DateDiff.inSeconds(d1, d2);
var dateOutput = "";
if (timeLaps<60)
{
dateOutput = timeLaps+" seconds";
}
else
{
timeLaps = DateDiff.inMinutes(d1, d2);
if (timeLaps<60)
{
dateOutput = timeLaps+" minutes";
}
else
{
timeLaps = DateDiff.inHours(d1, d2);
if (timeLaps<24)
{
dateOutput = timeLaps+" hours";
}
else
{
timeLaps = DateDiff.inDays(d1, d2);
if (timeLaps<7)
{
dateOutput = timeLaps+" days";
}
else
{
timeLaps = DateDiff.inWeeks(d1, d2);
if (timeLaps<4)
{
dateOutput = timeLaps+" weeks";
}
else
{
timeLaps = DateDiff.inMonths(d1, d2);
if (timeLaps<12)
{
dateOutput = timeLaps+" months";
}
else
{
timeLaps = DateDiff.inYears(d1, d2);
dateOutput = timeLaps+" years";
}
}
}
}
}
}
alert (dateOutput);
With momentjs it's simple:
moment("2016-04-08").fromNow();
function DateDiff(date1, date2) {
date1.setHours(0);
date1.setMinutes(0, 0, 0);
date2.setHours(0);
date2.setMinutes(0, 0, 0);
var datediff = Math.abs(date1.getTime() - date2.getTime()); // difference
return parseInt(datediff / (24 * 60 * 60 * 1000), 10); //Convert values days and return value
}
var d1=new Date(2011,0,1); // jan,1 2011
var d2=new Date(); // now
var diff=d2-d1,sign=diff<0?-1:1,milliseconds,seconds,minutes,hours,days;
diff/=sign; // or diff=Math.abs(diff);
diff=(diff-(milliseconds=diff%1000))/1000;
diff=(diff-(seconds=diff%60))/60;
diff=(diff-(minutes=diff%60))/60;
days=(diff-(hours=diff%24))/24;
console.info(sign===1?"Elapsed: ":"Remains: ",
days+" days, ",
hours+" hours, ",
minutes+" minutes, ",
seconds+" seconds, ",
milliseconds+" milliseconds.");
I think this should do it.
let today = new Date();
let form_date=new Date('2019-10-23')
let difference=form_date>today ? form_date-today : today-form_date
let diff_days=Math.floor(difference/(1000*3600*24))
based on javascript runtime prototype implementation you can use simple arithmetic to subtract dates as in bellow
var sep = new Date(2020, 07, 31, 23, 59, 59);
var today = new Date();
var diffD = Math.floor((sep - today) / (1000 * 60 * 60 * 24));
console.log('Day Diff: '+diffD);
the difference return answer as milliseconds, then you have to convert it by division:
by 1000 to convert to second
by 1000×60 convert to minute
by 1000×60×60 convert to hour
by 1000×60×60×24 convert to day
function DateDiff(b, e)
{
let
endYear = e.getFullYear(),
endMonth = e.getMonth(),
years = endYear - b.getFullYear(),
months = endMonth - b.getMonth(),
days = e.getDate() - b.getDate();
if (months < 0)
{
years--;
months += 12;
}
if (days < 0)
{
months--;
days += new Date(endYear, endMonth, 0).getDate();
}
return [years, months, days];
}
[years, months, days] = DateDiff(
new Date("October 21, 1980"),
new Date("July 11, 2017")); // 36 8 20
Sorry but flat millisecond calculation is not reliable
Thanks for all the responses, but few of the functions I tried are failing either on
1. A date near today's date
2. A date in 1970 or
3. A date in a leap year.
Approach that best worked for me and covers all scenario e.g. leap year, near date in 1970, feb 29 etc.
var someday = new Date("8/1/1985");
var today = new Date();
var years = today.getFullYear() - someday.getFullYear();
// Reset someday to the current year.
someday.setFullYear(today.getFullYear());
// Depending on when that day falls for this year, subtract 1.
if (today < someday)
{
years--;
}
document.write("Its been " + years + " full years.");
This code will return the difference between two dates in days:
const previous_date = new Date("2019-12-23");
const current_date = new Date();
const current_year = current_date.getFullYear();
const previous_date_year =
previous_date.getFullYear();
const difference_in_years = current_year -
previous_date_year;
let months = current_date.getMonth();
months = months + 1; // for making the indexing
// of months from 1
for(let i = 0; i < difference_in_years; i++){
months = months + 12;
}
let days = current_date.getDate();
days = days + (months * 30.417);
console.log(`The days between ${current_date} and
${previous_date} are : ${days} (approximately)`);
If you are using moment.js then it is pretty simple to find date difference.
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
This is how you can implement difference between dates without a framework.
function getDateDiff(dateOne, dateTwo) {
if(dateOne.charAt(2)=='-' & dateTwo.charAt(2)=='-'){
dateOne = new Date(formatDate(dateOne));
dateTwo = new Date(formatDate(dateTwo));
}
else{
dateOne = new Date(dateOne);
dateTwo = new Date(dateTwo);
}
let timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
let diffMonths = Math.ceil(diffDays/31);
let diffYears = Math.ceil(diffMonths/12);
let message = "Difference in Days: " + diffDays + " " +
"Difference in Months: " + diffMonths+ " " +
"Difference in Years: " + diffYears;
return message;
}
function formatDate(date) {
return date.split('-').reverse().join('-');
}
console.log(getDateDiff("23-04-2017", "23-04-2018"));
function daysInMonth (month, year) {
return new Date(year, month, 0).getDate();
}
function getduration(){
let A= document.getElementById("date1_id").value
let B= document.getElementById("date2_id").value
let C=Number(A.substring(3,5))
let D=Number(B.substring(3,5))
let dif=D-C
let arr=[];
let sum=0;
for (let i=0;i<dif+1;i++){
sum+=Number(daysInMonth(i+C,2019))
}
let sum_alter=0;
for (let i=0;i<dif;i++){
sum_alter+=Number(daysInMonth(i+C,2019))
}
let no_of_month=(Number(B.substring(3,5)) - Number(A.substring(3,5)))
let days=[];
if ((Number(B.substring(3,5)) - Number(A.substring(3,5)))>0||Number(B.substring(0,2)) - Number(A.substring(0,2))<0){
days=Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter
}
if ((Number(B.substring(3,5)) == Number(A.substring(3,5)))){
console.log(Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter)
}
time_1=[]; time_2=[]; let hour=[];
time_1=document.getElementById("time1_id").value
time_2=document.getElementById("time2_id").value
if (time_1.substring(0,2)=="12"){
time_1="00:00:00 PM"
}
if (time_1.substring(9,11)==time_2.substring(9,11)){
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))
}
if (time_1.substring(9,11)!=time_2.substring(9,11)){
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))+12
}
let min=Math.abs(Number(time_1.substring(3,5))-Number(time_2.substring(3,5)))
document.getElementById("duration_id").value=days +" days "+ hour+" hour " + min+" min "
}
<input type="text" id="date1_id" placeholder="28/05/2019">
<input type="text" id="date2_id" placeholder="29/06/2019">
<br><br>
<input type="text" id="time1_id" placeholder="08:01:00 AM">
<input type="text" id="time2_id" placeholder="00:00:00 PM">
<br><br>
<button class="text" onClick="getduration()">Submit </button>
<br><br>
<input type="text" id="duration_id" placeholder="days hour min">
var date1 = new Date("06/30/2019");
var date2 = new Date("07/30/2019");
// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
//To display the final no. of days (result)
document.write("Total number of days between dates <br>"
+ date1 + "<br> and <br>"
+ date2 + " is: <br> "
+ Difference_In_Days);
this should work just fine if you just need to show what time left, since JavaScript uses frames for its time you'll have get your End Time - The Time RN after that we can divide it by 1000 since apparently 1000 frames = 1 seconds, after that you can use the basic math of time, but there's still a problem to this code, since the calculation is static, it can't compensate for the different day total in a year (360/365/366), the bunch of IF after the calculation is to make it null if the time is lower than 0, hope this helps even though it's not exactly what you're asking :)
var now = new Date();
var end = new Date("End Time");
var total = (end - now) ;
var totalD = Math.abs(Math.floor(total/1000));
var years = Math.floor(totalD / (365*60*60*24));
var months = Math.floor((totalD - years*365*60*60*24) / (30*60*60*24));
var days = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24)/ (60*60*24));
var hours = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24)/ (60*60));
var minutes = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60)/ (60));
var seconds = Math.floor(totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60 - minutes*60);
var Y = years < 1 ? "" : years + " Years ";
var M = months < 1 ? "" : months + " Months ";
var D = days < 1 ? "" : days + " Days ";
var H = hours < 1 ? "" : hours + " Hours ";
var I = minutes < 1 ? "" : minutes + " Minutes ";
var S = seconds < 1 ? "" : seconds + " Seconds ";
var A = years == 0 && months == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0 ? "Sending" : " Remaining";
document.getElementById('txt').innerHTML = Y + M + D + H + I + S + A;
Ok, there are a bunch of ways you can do that.
Yes, you can use plain old JS. Just try:
let dt1 = new Date()
let dt2 = new Date()
Let's emulate passage using Date.prototype.setMinutes and make sure we are in range.
dt1.setMinutes(7)
dt2.setMinutes(42)
console.log('Elapsed seconds:',(dt2-dt1)/1000)
Alternatively you could use some library like js-joda, where you can easily do things like this (directly from docs):
var dt1 = LocalDateTime.parse("2016-02-26T23:55:42.123");
var dt2 = dt1
.plusYears(6)
.plusMonths(12)
.plusHours(2)
.plusMinutes(42)
.plusSeconds(12);
// obtain the duration between the two dates
dt1.until(dt2, ChronoUnit.YEARS); // 7
dt1.until(dt2, ChronoUnit.MONTHS); // 84
dt1.until(dt2, ChronoUnit.WEEKS); // 356
dt1.until(dt2, ChronoUnit.DAYS); // 2557
dt1.until(dt2, ChronoUnit.HOURS); // 61370
dt1.until(dt2, ChronoUnit.MINUTES); // 3682242
dt1.until(dt2, ChronoUnit.SECONDS); // 220934532
There are plenty more libraries ofc, but js-joda has an added bonus of being available also in Java, where it has been extensively tested. All those tests have been migrated to js-joda, it's also immutable.
I made a below function to get the difference between now and "2021-02-26T21:50:42.123".
The difference return answer as milliseconds, so I convert it by using this formula:
(1000 * 3600 * 24).
function getDiff(dateAcquired) {
let calDiff = Math.floor(
(new Date() - new Date(dateAcquired)) / (1000 * 3600 * 24)
);
return calDiff;
}
console.log(getDiff("2021-02-26T21:50:42.123"));
Can be useful :
const date_diff = (date1, date2) => Math.ceil(Math.abs(date1 - date2)/24 * 60 * 60 * 1000)
or
const date_diff = (date1, date2) => Math.ceil(Math.abs(date1 - date2)/86400000)
where 24 * 60 * 60 * 1000 is (day * minutes * seconds * milliseconds) = 86400000 milliseconds in one day
Thank you
// the idea is to get time left for new year.
// Not considering milliseconds as of now, but that
// can be done
var newYear = '1 Jan 2023';
const secondsInAMin = 60;
const secondsInAnHour = 60 * secondsInAMin;
const secondsInADay = 24 * secondsInAnHour;
function DateDiffJs() {
var newYearDate = new Date(newYear);
var currDate = new Date();
var remainingSecondsInDateDiff = (newYearDate - currDate) / 1000;
var days = Math.floor(remainingSecondsInDateDiff / secondsInADay);
var remainingSecondsAfterDays = remainingSecondsInDateDiff - (days * secondsInADay);
var hours = Math.floor(remainingSecondsAfterDays / secondsInAnHour);
var remainingSecondsAfterhours = remainingSecondsAfterDays - (hours * secondsInAnHour);
var mins = Math.floor(remainingSecondsAfterhours / secondsInAMin);
var seconds = Math.floor(remainingSecondsAfterhours - (mins * secondsInAMin));
console.log(`days :: ${days}`)
console.log(`hours :: ${hours}`)
console.log(`mins :: ${mins}`)
console.log(`seconds :: ${seconds}`)
}
DateDiffJs();

Not able to get the result date/hours [duplicate]

How can I calculate an age in years, given a birth date of format YYYYMMDD? Is it possible using the Date() function?
I am looking for a better solution than the one I am using now:
var dob = '19800810';
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
alert(age);
Try this.
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;
}
I believe the only thing that looked crude on your code was the substr part.
Fiddle: http://jsfiddle.net/codeandcloud/n33RJ/
I would go for readability:
function _calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Disclaimer: This also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).
Instead I would recommend using a library for this, if precision is very important. Also #Naveens post, is probably the most accurate, as it doesn't rely on the time of day.
Important: This answer doesn't provide an 100% accurate answer, it is off by around 10-20 hours depending on the date.
There are no better solutions ( not in these answers anyway ). - naveen
I of course couldn't resist the urge to take up the challenge and make a faster and shorter birthday calculator than the current accepted solution.
The main point for my solution, is that math is fast, so instead of using branching, and the date model javascript provides to calculate a solution we use the wonderful math
The answer looks like this, and runs ~65% faster than naveen's plus it's much shorter:
function calcAge(dateString) {
var birthday = +new Date(dateString);
return ~~((Date.now() - birthday) / (31557600000));
}
The magic number: 31557600000 is 24 * 3600 * 365.25 * 1000
Which is the length of a year, the length of a year is 365 days and 6 hours which is 0.25 day. In the end i floor the result which gives us the final age.
Here is the benchmarks: http://jsperf.com/birthday-calculation
To support OP's data format you can replace +new Date(dateString);
with +new Date(d.substr(0, 4), d.substr(4, 2)-1, d.substr(6, 2));
If you can come up with a better solution please share! :-)
Clean one-liner solution using ES6:
const getAge = birthDate => Math.floor((new Date() - new Date(birthDate).getTime()) / 3.15576e+10)
// today is 2018-06-13
getAge('1994-06-14') // 23
getAge('1994-06-13') // 24
I am using a year of 365.25 days (0.25 because of leap years) which are 3.15576e+10 milliseconds (365.25 * 24 * 60 * 60 * 1000) respectively.
It has a few hours margin so depending on the use case it may not be the best option.
With momentjs:
/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')
Some time ago I made a function with that purpose:
function getAge(birthDate) {
var now = new Date();
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// days since the birthdate
var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
var age = 0;
// iterate the years
for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
}
It takes a Date object as input, so you need to parse the 'YYYYMMDD' formatted date string:
var birthDateStr = '19840831',
parts = birthDateStr.match(/(\d{4})(\d{2})(\d{2})/),
dateObj = new Date(parts[1], parts[2]-1, parts[3]); // months 0-based!
getAge(dateObj); // 26
Here's my solution, just pass in a parseable date:
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
// ageMonth = age.getMonth(); // Accurate calculation of the month part of the age
// ageDay = age.getDate(); // Approximate calculation of the day part of the age
}
Alternate solution, because why not:
function calculateAgeInYears (date) {
var now = new Date();
var current_year = now.getFullYear();
var year_diff = current_year - date.getFullYear();
var birthday_this_year = new Date(current_year, date.getMonth(), date.getDate());
var has_had_birthday_this_year = (now >= birthday_this_year);
return has_had_birthday_this_year
? year_diff
: year_diff - 1;
}
function age()
{
var birthdate = $j('#birthDate').val(); // in "mm/dd/yyyy" format
var senddate = $j('#expireDate').val(); // in "mm/dd/yyyy" format
var x = birthdate.split("/");
var y = senddate.split("/");
var bdays = x[1];
var bmonths = x[0];
var byear = x[2];
//alert(bdays);
var sdays = y[1];
var smonths = y[0];
var syear = y[2];
//alert(sdays);
if(sdays < bdays)
{
sdays = parseInt(sdays) + 30;
smonths = parseInt(smonths) - 1;
//alert(sdays);
var fdays = sdays - bdays;
//alert(fdays);
}
else{
var fdays = sdays - bdays;
}
if(smonths < bmonths)
{
smonths = parseInt(smonths) + 12;
syear = syear - 1;
var fmonths = smonths - bmonths;
}
else
{
var fmonths = smonths - bmonths;
}
var fyear = syear - byear;
document.getElementById('patientAge').value = fyear+' years '+fmonths+' months '+fdays+' days';
}
I think that could be simply like that:
function age(dateString){
let birth = new Date(dateString);
let now = new Date();
let beforeBirth = ((() => {birth.setDate(now.getDate());birth.setMonth(now.getMonth()); return birth.getTime()})() < birth.getTime()) ? 0 : 1;
return now.getFullYear() - birth.getFullYear() - beforeBirth;
}
age('09/20/1981');
//35
Works also with a timestamp
age(403501000000)
//34
That's the most elegant way for me:
const getAge = (birthDateString) => {
const today = new Date();
const birthDate = new Date(birthDateString);
const yearsDifference = today.getFullYear() - birthDate.getFullYear();
if (
today.getMonth() < birthDate.getMonth() ||
(today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
) {
return yearsDifference - 1;
}
return yearsDifference;
};
console.log(getAge('2018-03-12'));
This question is over 10 years old an nobody has addressed the prompt that they already have the birth date in YYYYMMDD format?
If you have a past date and the current date both in YYYYMMDD format, you can very quickly calculate the number of years between them like this:
var pastDate = '20101030';
var currentDate = '20210622';
var years = Math.floor( ( currentDate - pastDate ) * 0.0001 );
// 10 (10.9592)
You can get the current date formatted as YYYYMMDD like this:
var now = new Date();
var currentDate = [
now.getFullYear(),
('0' + (now.getMonth() + 1) ).slice(-2),
('0' + now.getDate() ).slice(-2),
].join('');
To test whether the birthday already passed or not, I define a helper function Date.prototype.getDoY, which effectively returns the day number of the year. The rest is pretty self-explanatory.
Date.prototype.getDoY = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.floor(((this - onejan) / 86400000) + 1);
};
function getAge(birthDate) {
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
var now = new Date(),
age = now.getFullYear() - birthDate.getFullYear(),
doyNow = now.getDoY(),
doyBirth = birthDate.getDoY();
// normalize day-of-year in leap years
if (isLeap(now.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyNow--;
if (isLeap(birthDate.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyBirth--;
if (doyNow <= doyBirth)
age--; // birthday not yet passed this year, so -1
return age;
};
var myBirth = new Date(2001, 6, 4);
console.log(getAge(myBirth));
I just had to write this function for myself - the accepted answer is fairly good but IMO could use some cleanup. This takes a unix timestamp for dob because that was my requirement but could be quickly adapted to use a string:
var getAge = function(dob) {
var measureDays = function(dateObj) {
return 31*dateObj.getMonth()+dateObj.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - (measureDays(now) < measureDays(d));
}
Notice I've used a flat value of 31 in my measureDays function. All the calculation cares about is that the "day-of-year" be a monotonically increasing measure of the timestamp.
If using a javascript timestamp or string, obviously you'll want to remove the factor of 1000.
function getAge(dateString) {
var dates = dateString.split("-");
var d = new Date();
var userday = dates[0];
var usermonth = dates[1];
var useryear = dates[2];
var curday = d.getDate();
var curmonth = d.getMonth()+1;
var curyear = d.getFullYear();
var age = curyear - useryear;
if((curmonth < usermonth) || ( (curmonth == usermonth) && curday < userday )){
age--;
}
return age;
}
To get the age when european date has entered:
getAge('16-03-1989')
I've checked the examples showed before and they didn't worked in all cases, and because of this i made a script of my own. I tested this, and it works perfectly.
function getAge(birth) {
var today = new Date();
var curr_date = today.getDate();
var curr_month = today.getMonth() + 1;
var curr_year = today.getFullYear();
var pieces = birth.split('/');
var birth_date = pieces[0];
var birth_month = pieces[1];
var birth_year = pieces[2];
if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year-birth_year);
if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year-birth_year-1);
if (curr_month > birth_month) return parseInt(curr_year-birth_year);
if (curr_month < birth_month) return parseInt(curr_year-birth_year-1);
}
var age = getAge('18/01/2011');
alert(age);
Get the age (years, months and days) from the date of birth with javascript
Function calcularEdad (years, months and days)
function calcularEdad(fecha) {
// Si la fecha es correcta, calculamos la edad
if (typeof fecha != "string" && fecha && esNumero(fecha.getTime())) {
fecha = formatDate(fecha, "yyyy-MM-dd");
}
var values = fecha.split("-");
var dia = values[2];
var mes = values[1];
var ano = values[0];
// cogemos los valores actuales
var fecha_hoy = new Date();
var ahora_ano = fecha_hoy.getYear();
var ahora_mes = fecha_hoy.getMonth() + 1;
var ahora_dia = fecha_hoy.getDate();
// realizamos el calculo
var edad = (ahora_ano + 1900) - ano;
if (ahora_mes < mes) {
edad--;
}
if ((mes == ahora_mes) && (ahora_dia < dia)) {
edad--;
}
if (edad > 1900) {
edad -= 1900;
}
// calculamos los meses
var meses = 0;
if (ahora_mes > mes && dia > ahora_dia)
meses = ahora_mes - mes - 1;
else if (ahora_mes > mes)
meses = ahora_mes - mes
if (ahora_mes < mes && dia < ahora_dia)
meses = 12 - (mes - ahora_mes);
else if (ahora_mes < mes)
meses = 12 - (mes - ahora_mes + 1);
if (ahora_mes == mes && dia > ahora_dia)
meses = 11;
// calculamos los dias
var dias = 0;
if (ahora_dia > dia)
dias = ahora_dia - dia;
if (ahora_dia < dia) {
ultimoDiaMes = new Date(ahora_ano, ahora_mes - 1, 0);
dias = ultimoDiaMes.getDate() - (dia - ahora_dia);
}
return edad + " años, " + meses + " meses y " + dias + " días";
}
Function esNumero
function esNumero(strNumber) {
if (strNumber == null) return false;
if (strNumber == undefined) return false;
if (typeof strNumber === "number" && !isNaN(strNumber)) return true;
if (strNumber == "") return false;
if (strNumber === "") return false;
var psInt, psFloat;
psInt = parseInt(strNumber);
psFloat = parseFloat(strNumber);
return !isNaN(strNumber) && !isNaN(psFloat);
}
One more possible solution with moment.js:
var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5
I am a bit too late but I found this to be the simplest way to calculate a birth date.
Hopefully this will help.
function init() {
writeYears("myage", 0, Age());
}
function Age() {
var birthday = new Date(1997, 02, 01), //Year, month-1 , day.
today = new Date(),
one_year = 1000 * 60 * 60 * 24 * 365;
return Math.floor((today.getTime() - birthday.getTime()) / one_year);
}
function writeYears(id, current, maximum) {
document.getElementById(id).innerHTML = current;
if (current < maximum) {
setTimeout(function() {
writeYears(id, ++current, maximum);
}, Math.sin(current / maximum) * 200);
}
}
init()
<span id="myage"></span>
Works perfect for me, guys.
getAge(birthday) {
const millis = Date.now() - Date.parse(birthday);
return new Date(millis).getFullYear() - 1970;
}
I know this is a very old thread but I wanted to put in this implementation that I wrote for finding the age which I believe is much more accurate.
var getAge = function(year,month,date){
var today = new Date();
var dob = new Date();
dob.setFullYear(year);
dob.setMonth(month-1);
dob.setDate(date);
var timeDiff = today.valueOf() - dob.valueOf();
var milliInDay = 24*60*60*1000;
var noOfDays = timeDiff / milliInDay;
var daysInYear = 365.242;
return ( noOfDays / daysInYear ) ;
}
Ofcourse you could adapt this to fit in other formats of getting the parameters. Hope this helps someone looking for a better solution.
I used this approach using logic instead of math.
It's precise and quick.
The parameters are the year, month and day of the person's birthday.
It returns the person's age as an integer.
function calculateAge(year, month, day) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getUTCMonth() + 1;
var currentDay = currentDate.getUTCDate();
// You need to treat the cases where the year, month or day hasn't arrived yet.
var age = currentYear - year;
if (currentMonth > month) {
return age;
} else {
if (currentDay >= day) {
return age;
} else {
age--;
return age;
}
}
}
Adopting from naveen's and original OP's posts I ended up with a reusable method stub that accepts both strings and / or JS Date objects.
I named it gregorianAge() because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.
/**
* Calculates human age in years given a birth day. Optionally ageAtDate
* can be provided to calculate age at a specific date
*
* #param string|Date Object birthDate
* #param string|Date Object ageAtDate optional
* #returns integer Age between birthday and a given date or today
*/
function gregorianAge(birthDate, ageAtDate) {
// convert birthDate to date object if already not
if (Object.prototype.toString.call(birthDate) !== '[object Date]')
birthDate = new Date(birthDate);
// use today's date if ageAtDate is not provided
if (typeof ageAtDate == "undefined")
ageAtDate = new Date();
// convert ageAtDate to date object if already not
else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')
ageAtDate = new Date(ageAtDate);
// if conversion to date object fails return null
if (ageAtDate == null || birthDate == null)
return null;
var _m = ageAtDate.getMonth() - birthDate.getMonth();
// answer: ageAt year minus birth year less one (1) if month and day of
// ageAt year is before month and day of birth year
return (ageAtDate.getFullYear()) - birthDate.getFullYear()
- ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate())) ? 1 : 0)
}
// Below is for the attached snippet
function showAge() {
$('#age').text(gregorianAge($('#dob').val()))
}
$(function() {
$(".datepicker").datepicker();
showAge();
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
DOB:
<input name="dob" value="12/31/1970" id="dob" class="datepicker" onChange="showAge()" /> AGE: <span id="age"><span>
Two more options:
// Int Age to Date as string YYY-mm-dd
function age_to_date(age)
{
try {
var d = new Date();
var new_d = '';
d.setFullYear(d.getFullYear() - Math.abs(age));
new_d = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();
return new_d;
} catch(err) {
console.log(err.message);
}
}
// Date string (YYY-mm-dd) to Int age (years old)
function date_to_age(date)
{
try {
var today = new Date();
var d = new Date(date);
var year = today.getFullYear() - d.getFullYear();
var month = today.getMonth() - d.getMonth();
var day = today.getDate() - d.getDate();
var carry = 0;
if (year < 0)
return 0;
if (month <= 0 && day <= 0)
carry -= 1;
var age = parseInt(year);
age += carry;
return Math.abs(age);
} catch(err) {
console.log(err.message);
}
}
I've did some updated to one previous answer.
var calculateAge = function(dob) {
var days = function(date) {
return 31*date.getMonth() + date.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - ( measureDays(now) < measureDays(d));
}
I hope that helps :D
here is a simple way of calculating age:
//dob date dd/mm/yy
var d = 01/01/1990
//today
//date today string format
var today = new Date(); // i.e wed 04 may 2016 15:12:09 GMT
//todays year
var todayYear = today.getFullYear();
// today month
var todayMonth = today.getMonth();
//today date
var todayDate = today.getDate();
//dob
//dob parsed as date format
var dob = new Date(d);
// dob year
var dobYear = dob.getFullYear();
// dob month
var dobMonth = dob.getMonth();
//dob date
var dobDate = dob.getDate();
var yearsDiff = todayYear - dobYear ;
var age;
if ( todayMonth < dobMonth )
{
age = yearsDiff - 1;
}
else if ( todayMonth > dobMonth )
{
age = yearsDiff ;
}
else //if today month = dob month
{ if ( todayDate < dobDate )
{
age = yearsDiff - 1;
}
else
{
age = yearsDiff;
}
}
var now = DateTime.Now;
var age = DateTime.Now.Year - dob.Year;
if (now.Month < dob.Month || now.Month == dob.Month && now.Day < dob.Day) age--;
You may use this for age restriction in your form -
function dobvalidator(birthDateString){
strs = birthDateString.split("-");
var dd = strs[0];
var mm = strs[1];
var yy = strs[2];
var d = new Date();
var ds = d.getDate();
var ms = d.getMonth();
var ys = d.getFullYear();
var accepted_age = 18;
var days = ((accepted_age * 12) * 30) + (ms * 30) + ds;
var age = (((ys - yy) * 12) * 30) + ((12 - mm) * 30) + parseInt(30 - dd);
if((days - age) <= '0'){
console.log((days - age));
alert('You are at-least ' + accepted_age);
}else{
console.log((days - age));
alert('You are not at-least ' + accepted_age);
}
}
This is my modification:
function calculate_age(date) {
var today = new Date();
var today_month = today.getMonth() + 1; //STRANGE NUMBERING //January is 0!
var age = today.getYear() - date.getYear();
if ((today_month > date.getMonth() || ((today_month == date.getMonth()) && (today.getDate() < date.getDate())))) {
age--;
}
return age;
};
I believe that sometimes the readability is more important in this case. Unless we are validating 1000s of fields, this should be accurate and fast enough:
function is18orOlder(dateString) {
const dob = new Date(dateString);
const dobPlus18 = new Date(dob.getFullYear() + 18, dob.getMonth(), dob.getDate());
return dobPlus18 .valueOf() <= Date.now();
}
// Testing:
console.log(is18orOlder('01/01/1910')); // true
console.log(is18orOlder('01/01/2050')); // false
// When I'm posting this on 10/02/2020, so:
console.log(is18orOlder('10/08/2002')); // true
console.log(is18orOlder('10/19/2002')) // false
I like this approach instead of using a constant for how many ms are in a year, and later messing with the leap years, etc. Just letting the built-in Date to do the job.
Update, posting this snippet since one may found it useful. Since I'm enforcing a mask on the input field, to have the format of mm/dd/yyyy and already validating if the date is valid, in my case, this works too to validate 18+ years:
function is18orOlder(dateString) {
const [month, date, year] = value.split('/');
return new Date(+year + 13, +month, +date).valueOf() <= Date.now();
}

calculating age in javasctipt using 365.25 * 24 * 60 * 60 * 1000 [duplicate]

How can I calculate an age in years, given a birth date of format YYYYMMDD? Is it possible using the Date() function?
I am looking for a better solution than the one I am using now:
var dob = '19800810';
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
alert(age);
Try this.
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;
}
I believe the only thing that looked crude on your code was the substr part.
Fiddle: http://jsfiddle.net/codeandcloud/n33RJ/
I would go for readability:
function _calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Disclaimer: This also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).
Instead I would recommend using a library for this, if precision is very important. Also #Naveens post, is probably the most accurate, as it doesn't rely on the time of day.
Important: This answer doesn't provide an 100% accurate answer, it is off by around 10-20 hours depending on the date.
There are no better solutions ( not in these answers anyway ). - naveen
I of course couldn't resist the urge to take up the challenge and make a faster and shorter birthday calculator than the current accepted solution.
The main point for my solution, is that math is fast, so instead of using branching, and the date model javascript provides to calculate a solution we use the wonderful math
The answer looks like this, and runs ~65% faster than naveen's plus it's much shorter:
function calcAge(dateString) {
var birthday = +new Date(dateString);
return ~~((Date.now() - birthday) / (31557600000));
}
The magic number: 31557600000 is 24 * 3600 * 365.25 * 1000
Which is the length of a year, the length of a year is 365 days and 6 hours which is 0.25 day. In the end i floor the result which gives us the final age.
Here is the benchmarks: http://jsperf.com/birthday-calculation
To support OP's data format you can replace +new Date(dateString);
with +new Date(d.substr(0, 4), d.substr(4, 2)-1, d.substr(6, 2));
If you can come up with a better solution please share! :-)
Clean one-liner solution using ES6:
const getAge = birthDate => Math.floor((new Date() - new Date(birthDate).getTime()) / 3.15576e+10)
// today is 2018-06-13
getAge('1994-06-14') // 23
getAge('1994-06-13') // 24
I am using a year of 365.25 days (0.25 because of leap years) which are 3.15576e+10 milliseconds (365.25 * 24 * 60 * 60 * 1000) respectively.
It has a few hours margin so depending on the use case it may not be the best option.
With momentjs:
/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')
Some time ago I made a function with that purpose:
function getAge(birthDate) {
var now = new Date();
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// days since the birthdate
var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
var age = 0;
// iterate the years
for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
}
It takes a Date object as input, so you need to parse the 'YYYYMMDD' formatted date string:
var birthDateStr = '19840831',
parts = birthDateStr.match(/(\d{4})(\d{2})(\d{2})/),
dateObj = new Date(parts[1], parts[2]-1, parts[3]); // months 0-based!
getAge(dateObj); // 26
Here's my solution, just pass in a parseable date:
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
// ageMonth = age.getMonth(); // Accurate calculation of the month part of the age
// ageDay = age.getDate(); // Approximate calculation of the day part of the age
}
Alternate solution, because why not:
function calculateAgeInYears (date) {
var now = new Date();
var current_year = now.getFullYear();
var year_diff = current_year - date.getFullYear();
var birthday_this_year = new Date(current_year, date.getMonth(), date.getDate());
var has_had_birthday_this_year = (now >= birthday_this_year);
return has_had_birthday_this_year
? year_diff
: year_diff - 1;
}
function age()
{
var birthdate = $j('#birthDate').val(); // in "mm/dd/yyyy" format
var senddate = $j('#expireDate').val(); // in "mm/dd/yyyy" format
var x = birthdate.split("/");
var y = senddate.split("/");
var bdays = x[1];
var bmonths = x[0];
var byear = x[2];
//alert(bdays);
var sdays = y[1];
var smonths = y[0];
var syear = y[2];
//alert(sdays);
if(sdays < bdays)
{
sdays = parseInt(sdays) + 30;
smonths = parseInt(smonths) - 1;
//alert(sdays);
var fdays = sdays - bdays;
//alert(fdays);
}
else{
var fdays = sdays - bdays;
}
if(smonths < bmonths)
{
smonths = parseInt(smonths) + 12;
syear = syear - 1;
var fmonths = smonths - bmonths;
}
else
{
var fmonths = smonths - bmonths;
}
var fyear = syear - byear;
document.getElementById('patientAge').value = fyear+' years '+fmonths+' months '+fdays+' days';
}
I think that could be simply like that:
function age(dateString){
let birth = new Date(dateString);
let now = new Date();
let beforeBirth = ((() => {birth.setDate(now.getDate());birth.setMonth(now.getMonth()); return birth.getTime()})() < birth.getTime()) ? 0 : 1;
return now.getFullYear() - birth.getFullYear() - beforeBirth;
}
age('09/20/1981');
//35
Works also with a timestamp
age(403501000000)
//34
That's the most elegant way for me:
const getAge = (birthDateString) => {
const today = new Date();
const birthDate = new Date(birthDateString);
const yearsDifference = today.getFullYear() - birthDate.getFullYear();
if (
today.getMonth() < birthDate.getMonth() ||
(today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
) {
return yearsDifference - 1;
}
return yearsDifference;
};
console.log(getAge('2018-03-12'));
This question is over 10 years old an nobody has addressed the prompt that they already have the birth date in YYYYMMDD format?
If you have a past date and the current date both in YYYYMMDD format, you can very quickly calculate the number of years between them like this:
var pastDate = '20101030';
var currentDate = '20210622';
var years = Math.floor( ( currentDate - pastDate ) * 0.0001 );
// 10 (10.9592)
You can get the current date formatted as YYYYMMDD like this:
var now = new Date();
var currentDate = [
now.getFullYear(),
('0' + (now.getMonth() + 1) ).slice(-2),
('0' + now.getDate() ).slice(-2),
].join('');
To test whether the birthday already passed or not, I define a helper function Date.prototype.getDoY, which effectively returns the day number of the year. The rest is pretty self-explanatory.
Date.prototype.getDoY = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.floor(((this - onejan) / 86400000) + 1);
};
function getAge(birthDate) {
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
var now = new Date(),
age = now.getFullYear() - birthDate.getFullYear(),
doyNow = now.getDoY(),
doyBirth = birthDate.getDoY();
// normalize day-of-year in leap years
if (isLeap(now.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyNow--;
if (isLeap(birthDate.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyBirth--;
if (doyNow <= doyBirth)
age--; // birthday not yet passed this year, so -1
return age;
};
var myBirth = new Date(2001, 6, 4);
console.log(getAge(myBirth));
I just had to write this function for myself - the accepted answer is fairly good but IMO could use some cleanup. This takes a unix timestamp for dob because that was my requirement but could be quickly adapted to use a string:
var getAge = function(dob) {
var measureDays = function(dateObj) {
return 31*dateObj.getMonth()+dateObj.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - (measureDays(now) < measureDays(d));
}
Notice I've used a flat value of 31 in my measureDays function. All the calculation cares about is that the "day-of-year" be a monotonically increasing measure of the timestamp.
If using a javascript timestamp or string, obviously you'll want to remove the factor of 1000.
function getAge(dateString) {
var dates = dateString.split("-");
var d = new Date();
var userday = dates[0];
var usermonth = dates[1];
var useryear = dates[2];
var curday = d.getDate();
var curmonth = d.getMonth()+1;
var curyear = d.getFullYear();
var age = curyear - useryear;
if((curmonth < usermonth) || ( (curmonth == usermonth) && curday < userday )){
age--;
}
return age;
}
To get the age when european date has entered:
getAge('16-03-1989')
I've checked the examples showed before and they didn't worked in all cases, and because of this i made a script of my own. I tested this, and it works perfectly.
function getAge(birth) {
var today = new Date();
var curr_date = today.getDate();
var curr_month = today.getMonth() + 1;
var curr_year = today.getFullYear();
var pieces = birth.split('/');
var birth_date = pieces[0];
var birth_month = pieces[1];
var birth_year = pieces[2];
if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year-birth_year);
if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year-birth_year-1);
if (curr_month > birth_month) return parseInt(curr_year-birth_year);
if (curr_month < birth_month) return parseInt(curr_year-birth_year-1);
}
var age = getAge('18/01/2011');
alert(age);
Get the age (years, months and days) from the date of birth with javascript
Function calcularEdad (years, months and days)
function calcularEdad(fecha) {
// Si la fecha es correcta, calculamos la edad
if (typeof fecha != "string" && fecha && esNumero(fecha.getTime())) {
fecha = formatDate(fecha, "yyyy-MM-dd");
}
var values = fecha.split("-");
var dia = values[2];
var mes = values[1];
var ano = values[0];
// cogemos los valores actuales
var fecha_hoy = new Date();
var ahora_ano = fecha_hoy.getYear();
var ahora_mes = fecha_hoy.getMonth() + 1;
var ahora_dia = fecha_hoy.getDate();
// realizamos el calculo
var edad = (ahora_ano + 1900) - ano;
if (ahora_mes < mes) {
edad--;
}
if ((mes == ahora_mes) && (ahora_dia < dia)) {
edad--;
}
if (edad > 1900) {
edad -= 1900;
}
// calculamos los meses
var meses = 0;
if (ahora_mes > mes && dia > ahora_dia)
meses = ahora_mes - mes - 1;
else if (ahora_mes > mes)
meses = ahora_mes - mes
if (ahora_mes < mes && dia < ahora_dia)
meses = 12 - (mes - ahora_mes);
else if (ahora_mes < mes)
meses = 12 - (mes - ahora_mes + 1);
if (ahora_mes == mes && dia > ahora_dia)
meses = 11;
// calculamos los dias
var dias = 0;
if (ahora_dia > dia)
dias = ahora_dia - dia;
if (ahora_dia < dia) {
ultimoDiaMes = new Date(ahora_ano, ahora_mes - 1, 0);
dias = ultimoDiaMes.getDate() - (dia - ahora_dia);
}
return edad + " años, " + meses + " meses y " + dias + " días";
}
Function esNumero
function esNumero(strNumber) {
if (strNumber == null) return false;
if (strNumber == undefined) return false;
if (typeof strNumber === "number" && !isNaN(strNumber)) return true;
if (strNumber == "") return false;
if (strNumber === "") return false;
var psInt, psFloat;
psInt = parseInt(strNumber);
psFloat = parseFloat(strNumber);
return !isNaN(strNumber) && !isNaN(psFloat);
}
One more possible solution with moment.js:
var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5
I am a bit too late but I found this to be the simplest way to calculate a birth date.
Hopefully this will help.
function init() {
writeYears("myage", 0, Age());
}
function Age() {
var birthday = new Date(1997, 02, 01), //Year, month-1 , day.
today = new Date(),
one_year = 1000 * 60 * 60 * 24 * 365;
return Math.floor((today.getTime() - birthday.getTime()) / one_year);
}
function writeYears(id, current, maximum) {
document.getElementById(id).innerHTML = current;
if (current < maximum) {
setTimeout(function() {
writeYears(id, ++current, maximum);
}, Math.sin(current / maximum) * 200);
}
}
init()
<span id="myage"></span>
Works perfect for me, guys.
getAge(birthday) {
const millis = Date.now() - Date.parse(birthday);
return new Date(millis).getFullYear() - 1970;
}
I know this is a very old thread but I wanted to put in this implementation that I wrote for finding the age which I believe is much more accurate.
var getAge = function(year,month,date){
var today = new Date();
var dob = new Date();
dob.setFullYear(year);
dob.setMonth(month-1);
dob.setDate(date);
var timeDiff = today.valueOf() - dob.valueOf();
var milliInDay = 24*60*60*1000;
var noOfDays = timeDiff / milliInDay;
var daysInYear = 365.242;
return ( noOfDays / daysInYear ) ;
}
Ofcourse you could adapt this to fit in other formats of getting the parameters. Hope this helps someone looking for a better solution.
I used this approach using logic instead of math.
It's precise and quick.
The parameters are the year, month and day of the person's birthday.
It returns the person's age as an integer.
function calculateAge(year, month, day) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getUTCMonth() + 1;
var currentDay = currentDate.getUTCDate();
// You need to treat the cases where the year, month or day hasn't arrived yet.
var age = currentYear - year;
if (currentMonth > month) {
return age;
} else {
if (currentDay >= day) {
return age;
} else {
age--;
return age;
}
}
}
Adopting from naveen's and original OP's posts I ended up with a reusable method stub that accepts both strings and / or JS Date objects.
I named it gregorianAge() because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.
/**
* Calculates human age in years given a birth day. Optionally ageAtDate
* can be provided to calculate age at a specific date
*
* #param string|Date Object birthDate
* #param string|Date Object ageAtDate optional
* #returns integer Age between birthday and a given date or today
*/
function gregorianAge(birthDate, ageAtDate) {
// convert birthDate to date object if already not
if (Object.prototype.toString.call(birthDate) !== '[object Date]')
birthDate = new Date(birthDate);
// use today's date if ageAtDate is not provided
if (typeof ageAtDate == "undefined")
ageAtDate = new Date();
// convert ageAtDate to date object if already not
else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')
ageAtDate = new Date(ageAtDate);
// if conversion to date object fails return null
if (ageAtDate == null || birthDate == null)
return null;
var _m = ageAtDate.getMonth() - birthDate.getMonth();
// answer: ageAt year minus birth year less one (1) if month and day of
// ageAt year is before month and day of birth year
return (ageAtDate.getFullYear()) - birthDate.getFullYear()
- ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate())) ? 1 : 0)
}
// Below is for the attached snippet
function showAge() {
$('#age').text(gregorianAge($('#dob').val()))
}
$(function() {
$(".datepicker").datepicker();
showAge();
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
DOB:
<input name="dob" value="12/31/1970" id="dob" class="datepicker" onChange="showAge()" /> AGE: <span id="age"><span>
Two more options:
// Int Age to Date as string YYY-mm-dd
function age_to_date(age)
{
try {
var d = new Date();
var new_d = '';
d.setFullYear(d.getFullYear() - Math.abs(age));
new_d = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();
return new_d;
} catch(err) {
console.log(err.message);
}
}
// Date string (YYY-mm-dd) to Int age (years old)
function date_to_age(date)
{
try {
var today = new Date();
var d = new Date(date);
var year = today.getFullYear() - d.getFullYear();
var month = today.getMonth() - d.getMonth();
var day = today.getDate() - d.getDate();
var carry = 0;
if (year < 0)
return 0;
if (month <= 0 && day <= 0)
carry -= 1;
var age = parseInt(year);
age += carry;
return Math.abs(age);
} catch(err) {
console.log(err.message);
}
}
I've did some updated to one previous answer.
var calculateAge = function(dob) {
var days = function(date) {
return 31*date.getMonth() + date.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - ( measureDays(now) < measureDays(d));
}
I hope that helps :D
here is a simple way of calculating age:
//dob date dd/mm/yy
var d = 01/01/1990
//today
//date today string format
var today = new Date(); // i.e wed 04 may 2016 15:12:09 GMT
//todays year
var todayYear = today.getFullYear();
// today month
var todayMonth = today.getMonth();
//today date
var todayDate = today.getDate();
//dob
//dob parsed as date format
var dob = new Date(d);
// dob year
var dobYear = dob.getFullYear();
// dob month
var dobMonth = dob.getMonth();
//dob date
var dobDate = dob.getDate();
var yearsDiff = todayYear - dobYear ;
var age;
if ( todayMonth < dobMonth )
{
age = yearsDiff - 1;
}
else if ( todayMonth > dobMonth )
{
age = yearsDiff ;
}
else //if today month = dob month
{ if ( todayDate < dobDate )
{
age = yearsDiff - 1;
}
else
{
age = yearsDiff;
}
}
var now = DateTime.Now;
var age = DateTime.Now.Year - dob.Year;
if (now.Month < dob.Month || now.Month == dob.Month && now.Day < dob.Day) age--;
You may use this for age restriction in your form -
function dobvalidator(birthDateString){
strs = birthDateString.split("-");
var dd = strs[0];
var mm = strs[1];
var yy = strs[2];
var d = new Date();
var ds = d.getDate();
var ms = d.getMonth();
var ys = d.getFullYear();
var accepted_age = 18;
var days = ((accepted_age * 12) * 30) + (ms * 30) + ds;
var age = (((ys - yy) * 12) * 30) + ((12 - mm) * 30) + parseInt(30 - dd);
if((days - age) <= '0'){
console.log((days - age));
alert('You are at-least ' + accepted_age);
}else{
console.log((days - age));
alert('You are not at-least ' + accepted_age);
}
}
This is my modification:
function calculate_age(date) {
var today = new Date();
var today_month = today.getMonth() + 1; //STRANGE NUMBERING //January is 0!
var age = today.getYear() - date.getYear();
if ((today_month > date.getMonth() || ((today_month == date.getMonth()) && (today.getDate() < date.getDate())))) {
age--;
}
return age;
};
I believe that sometimes the readability is more important in this case. Unless we are validating 1000s of fields, this should be accurate and fast enough:
function is18orOlder(dateString) {
const dob = new Date(dateString);
const dobPlus18 = new Date(dob.getFullYear() + 18, dob.getMonth(), dob.getDate());
return dobPlus18 .valueOf() <= Date.now();
}
// Testing:
console.log(is18orOlder('01/01/1910')); // true
console.log(is18orOlder('01/01/2050')); // false
// When I'm posting this on 10/02/2020, so:
console.log(is18orOlder('10/08/2002')); // true
console.log(is18orOlder('10/19/2002')) // false
I like this approach instead of using a constant for how many ms are in a year, and later messing with the leap years, etc. Just letting the built-in Date to do the job.
Update, posting this snippet since one may found it useful. Since I'm enforcing a mask on the input field, to have the format of mm/dd/yyyy and already validating if the date is valid, in my case, this works too to validate 18+ years:
function is18orOlder(dateString) {
const [month, date, year] = value.split('/');
return new Date(+year + 13, +month, +date).valueOf() <= Date.now();
}

Calculate age depending upon current date & birth Date [duplicate]

How can I calculate an age in years, given a birth date of format YYYYMMDD? Is it possible using the Date() function?
I am looking for a better solution than the one I am using now:
var dob = '19800810';
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
alert(age);
Try this.
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;
}
I believe the only thing that looked crude on your code was the substr part.
Fiddle: http://jsfiddle.net/codeandcloud/n33RJ/
I would go for readability:
function _calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Disclaimer: This also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).
Instead I would recommend using a library for this, if precision is very important. Also #Naveens post, is probably the most accurate, as it doesn't rely on the time of day.
Important: This answer doesn't provide an 100% accurate answer, it is off by around 10-20 hours depending on the date.
There are no better solutions ( not in these answers anyway ). - naveen
I of course couldn't resist the urge to take up the challenge and make a faster and shorter birthday calculator than the current accepted solution.
The main point for my solution, is that math is fast, so instead of using branching, and the date model javascript provides to calculate a solution we use the wonderful math
The answer looks like this, and runs ~65% faster than naveen's plus it's much shorter:
function calcAge(dateString) {
var birthday = +new Date(dateString);
return ~~((Date.now() - birthday) / (31557600000));
}
The magic number: 31557600000 is 24 * 3600 * 365.25 * 1000
Which is the length of a year, the length of a year is 365 days and 6 hours which is 0.25 day. In the end i floor the result which gives us the final age.
Here is the benchmarks: http://jsperf.com/birthday-calculation
To support OP's data format you can replace +new Date(dateString);
with +new Date(d.substr(0, 4), d.substr(4, 2)-1, d.substr(6, 2));
If you can come up with a better solution please share! :-)
Clean one-liner solution using ES6:
const getAge = birthDate => Math.floor((new Date() - new Date(birthDate).getTime()) / 3.15576e+10)
// today is 2018-06-13
getAge('1994-06-14') // 23
getAge('1994-06-13') // 24
I am using a year of 365.25 days (0.25 because of leap years) which are 3.15576e+10 milliseconds (365.25 * 24 * 60 * 60 * 1000) respectively.
It has a few hours margin so depending on the use case it may not be the best option.
With momentjs:
/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')
Some time ago I made a function with that purpose:
function getAge(birthDate) {
var now = new Date();
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// days since the birthdate
var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
var age = 0;
// iterate the years
for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
}
It takes a Date object as input, so you need to parse the 'YYYYMMDD' formatted date string:
var birthDateStr = '19840831',
parts = birthDateStr.match(/(\d{4})(\d{2})(\d{2})/),
dateObj = new Date(parts[1], parts[2]-1, parts[3]); // months 0-based!
getAge(dateObj); // 26
Here's my solution, just pass in a parseable date:
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
// ageMonth = age.getMonth(); // Accurate calculation of the month part of the age
// ageDay = age.getDate(); // Approximate calculation of the day part of the age
}
Alternate solution, because why not:
function calculateAgeInYears (date) {
var now = new Date();
var current_year = now.getFullYear();
var year_diff = current_year - date.getFullYear();
var birthday_this_year = new Date(current_year, date.getMonth(), date.getDate());
var has_had_birthday_this_year = (now >= birthday_this_year);
return has_had_birthday_this_year
? year_diff
: year_diff - 1;
}
function age()
{
var birthdate = $j('#birthDate').val(); // in "mm/dd/yyyy" format
var senddate = $j('#expireDate').val(); // in "mm/dd/yyyy" format
var x = birthdate.split("/");
var y = senddate.split("/");
var bdays = x[1];
var bmonths = x[0];
var byear = x[2];
//alert(bdays);
var sdays = y[1];
var smonths = y[0];
var syear = y[2];
//alert(sdays);
if(sdays < bdays)
{
sdays = parseInt(sdays) + 30;
smonths = parseInt(smonths) - 1;
//alert(sdays);
var fdays = sdays - bdays;
//alert(fdays);
}
else{
var fdays = sdays - bdays;
}
if(smonths < bmonths)
{
smonths = parseInt(smonths) + 12;
syear = syear - 1;
var fmonths = smonths - bmonths;
}
else
{
var fmonths = smonths - bmonths;
}
var fyear = syear - byear;
document.getElementById('patientAge').value = fyear+' years '+fmonths+' months '+fdays+' days';
}
I think that could be simply like that:
function age(dateString){
let birth = new Date(dateString);
let now = new Date();
let beforeBirth = ((() => {birth.setDate(now.getDate());birth.setMonth(now.getMonth()); return birth.getTime()})() < birth.getTime()) ? 0 : 1;
return now.getFullYear() - birth.getFullYear() - beforeBirth;
}
age('09/20/1981');
//35
Works also with a timestamp
age(403501000000)
//34
That's the most elegant way for me:
const getAge = (birthDateString) => {
const today = new Date();
const birthDate = new Date(birthDateString);
const yearsDifference = today.getFullYear() - birthDate.getFullYear();
if (
today.getMonth() < birthDate.getMonth() ||
(today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
) {
return yearsDifference - 1;
}
return yearsDifference;
};
console.log(getAge('2018-03-12'));
This question is over 10 years old an nobody has addressed the prompt that they already have the birth date in YYYYMMDD format?
If you have a past date and the current date both in YYYYMMDD format, you can very quickly calculate the number of years between them like this:
var pastDate = '20101030';
var currentDate = '20210622';
var years = Math.floor( ( currentDate - pastDate ) * 0.0001 );
// 10 (10.9592)
You can get the current date formatted as YYYYMMDD like this:
var now = new Date();
var currentDate = [
now.getFullYear(),
('0' + (now.getMonth() + 1) ).slice(-2),
('0' + now.getDate() ).slice(-2),
].join('');
To test whether the birthday already passed or not, I define a helper function Date.prototype.getDoY, which effectively returns the day number of the year. The rest is pretty self-explanatory.
Date.prototype.getDoY = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.floor(((this - onejan) / 86400000) + 1);
};
function getAge(birthDate) {
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
var now = new Date(),
age = now.getFullYear() - birthDate.getFullYear(),
doyNow = now.getDoY(),
doyBirth = birthDate.getDoY();
// normalize day-of-year in leap years
if (isLeap(now.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyNow--;
if (isLeap(birthDate.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyBirth--;
if (doyNow <= doyBirth)
age--; // birthday not yet passed this year, so -1
return age;
};
var myBirth = new Date(2001, 6, 4);
console.log(getAge(myBirth));
I just had to write this function for myself - the accepted answer is fairly good but IMO could use some cleanup. This takes a unix timestamp for dob because that was my requirement but could be quickly adapted to use a string:
var getAge = function(dob) {
var measureDays = function(dateObj) {
return 31*dateObj.getMonth()+dateObj.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - (measureDays(now) < measureDays(d));
}
Notice I've used a flat value of 31 in my measureDays function. All the calculation cares about is that the "day-of-year" be a monotonically increasing measure of the timestamp.
If using a javascript timestamp or string, obviously you'll want to remove the factor of 1000.
function getAge(dateString) {
var dates = dateString.split("-");
var d = new Date();
var userday = dates[0];
var usermonth = dates[1];
var useryear = dates[2];
var curday = d.getDate();
var curmonth = d.getMonth()+1;
var curyear = d.getFullYear();
var age = curyear - useryear;
if((curmonth < usermonth) || ( (curmonth == usermonth) && curday < userday )){
age--;
}
return age;
}
To get the age when european date has entered:
getAge('16-03-1989')
I've checked the examples showed before and they didn't worked in all cases, and because of this i made a script of my own. I tested this, and it works perfectly.
function getAge(birth) {
var today = new Date();
var curr_date = today.getDate();
var curr_month = today.getMonth() + 1;
var curr_year = today.getFullYear();
var pieces = birth.split('/');
var birth_date = pieces[0];
var birth_month = pieces[1];
var birth_year = pieces[2];
if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year-birth_year);
if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year-birth_year-1);
if (curr_month > birth_month) return parseInt(curr_year-birth_year);
if (curr_month < birth_month) return parseInt(curr_year-birth_year-1);
}
var age = getAge('18/01/2011');
alert(age);
Get the age (years, months and days) from the date of birth with javascript
Function calcularEdad (years, months and days)
function calcularEdad(fecha) {
// Si la fecha es correcta, calculamos la edad
if (typeof fecha != "string" && fecha && esNumero(fecha.getTime())) {
fecha = formatDate(fecha, "yyyy-MM-dd");
}
var values = fecha.split("-");
var dia = values[2];
var mes = values[1];
var ano = values[0];
// cogemos los valores actuales
var fecha_hoy = new Date();
var ahora_ano = fecha_hoy.getYear();
var ahora_mes = fecha_hoy.getMonth() + 1;
var ahora_dia = fecha_hoy.getDate();
// realizamos el calculo
var edad = (ahora_ano + 1900) - ano;
if (ahora_mes < mes) {
edad--;
}
if ((mes == ahora_mes) && (ahora_dia < dia)) {
edad--;
}
if (edad > 1900) {
edad -= 1900;
}
// calculamos los meses
var meses = 0;
if (ahora_mes > mes && dia > ahora_dia)
meses = ahora_mes - mes - 1;
else if (ahora_mes > mes)
meses = ahora_mes - mes
if (ahora_mes < mes && dia < ahora_dia)
meses = 12 - (mes - ahora_mes);
else if (ahora_mes < mes)
meses = 12 - (mes - ahora_mes + 1);
if (ahora_mes == mes && dia > ahora_dia)
meses = 11;
// calculamos los dias
var dias = 0;
if (ahora_dia > dia)
dias = ahora_dia - dia;
if (ahora_dia < dia) {
ultimoDiaMes = new Date(ahora_ano, ahora_mes - 1, 0);
dias = ultimoDiaMes.getDate() - (dia - ahora_dia);
}
return edad + " años, " + meses + " meses y " + dias + " días";
}
Function esNumero
function esNumero(strNumber) {
if (strNumber == null) return false;
if (strNumber == undefined) return false;
if (typeof strNumber === "number" && !isNaN(strNumber)) return true;
if (strNumber == "") return false;
if (strNumber === "") return false;
var psInt, psFloat;
psInt = parseInt(strNumber);
psFloat = parseFloat(strNumber);
return !isNaN(strNumber) && !isNaN(psFloat);
}
One more possible solution with moment.js:
var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5
I am a bit too late but I found this to be the simplest way to calculate a birth date.
Hopefully this will help.
function init() {
writeYears("myage", 0, Age());
}
function Age() {
var birthday = new Date(1997, 02, 01), //Year, month-1 , day.
today = new Date(),
one_year = 1000 * 60 * 60 * 24 * 365;
return Math.floor((today.getTime() - birthday.getTime()) / one_year);
}
function writeYears(id, current, maximum) {
document.getElementById(id).innerHTML = current;
if (current < maximum) {
setTimeout(function() {
writeYears(id, ++current, maximum);
}, Math.sin(current / maximum) * 200);
}
}
init()
<span id="myage"></span>
Works perfect for me, guys.
getAge(birthday) {
const millis = Date.now() - Date.parse(birthday);
return new Date(millis).getFullYear() - 1970;
}
I know this is a very old thread but I wanted to put in this implementation that I wrote for finding the age which I believe is much more accurate.
var getAge = function(year,month,date){
var today = new Date();
var dob = new Date();
dob.setFullYear(year);
dob.setMonth(month-1);
dob.setDate(date);
var timeDiff = today.valueOf() - dob.valueOf();
var milliInDay = 24*60*60*1000;
var noOfDays = timeDiff / milliInDay;
var daysInYear = 365.242;
return ( noOfDays / daysInYear ) ;
}
Ofcourse you could adapt this to fit in other formats of getting the parameters. Hope this helps someone looking for a better solution.
I used this approach using logic instead of math.
It's precise and quick.
The parameters are the year, month and day of the person's birthday.
It returns the person's age as an integer.
function calculateAge(year, month, day) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getUTCMonth() + 1;
var currentDay = currentDate.getUTCDate();
// You need to treat the cases where the year, month or day hasn't arrived yet.
var age = currentYear - year;
if (currentMonth > month) {
return age;
} else {
if (currentDay >= day) {
return age;
} else {
age--;
return age;
}
}
}
Adopting from naveen's and original OP's posts I ended up with a reusable method stub that accepts both strings and / or JS Date objects.
I named it gregorianAge() because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.
/**
* Calculates human age in years given a birth day. Optionally ageAtDate
* can be provided to calculate age at a specific date
*
* #param string|Date Object birthDate
* #param string|Date Object ageAtDate optional
* #returns integer Age between birthday and a given date or today
*/
function gregorianAge(birthDate, ageAtDate) {
// convert birthDate to date object if already not
if (Object.prototype.toString.call(birthDate) !== '[object Date]')
birthDate = new Date(birthDate);
// use today's date if ageAtDate is not provided
if (typeof ageAtDate == "undefined")
ageAtDate = new Date();
// convert ageAtDate to date object if already not
else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')
ageAtDate = new Date(ageAtDate);
// if conversion to date object fails return null
if (ageAtDate == null || birthDate == null)
return null;
var _m = ageAtDate.getMonth() - birthDate.getMonth();
// answer: ageAt year minus birth year less one (1) if month and day of
// ageAt year is before month and day of birth year
return (ageAtDate.getFullYear()) - birthDate.getFullYear()
- ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate())) ? 1 : 0)
}
// Below is for the attached snippet
function showAge() {
$('#age').text(gregorianAge($('#dob').val()))
}
$(function() {
$(".datepicker").datepicker();
showAge();
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
DOB:
<input name="dob" value="12/31/1970" id="dob" class="datepicker" onChange="showAge()" /> AGE: <span id="age"><span>
Two more options:
// Int Age to Date as string YYY-mm-dd
function age_to_date(age)
{
try {
var d = new Date();
var new_d = '';
d.setFullYear(d.getFullYear() - Math.abs(age));
new_d = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();
return new_d;
} catch(err) {
console.log(err.message);
}
}
// Date string (YYY-mm-dd) to Int age (years old)
function date_to_age(date)
{
try {
var today = new Date();
var d = new Date(date);
var year = today.getFullYear() - d.getFullYear();
var month = today.getMonth() - d.getMonth();
var day = today.getDate() - d.getDate();
var carry = 0;
if (year < 0)
return 0;
if (month <= 0 && day <= 0)
carry -= 1;
var age = parseInt(year);
age += carry;
return Math.abs(age);
} catch(err) {
console.log(err.message);
}
}
I've did some updated to one previous answer.
var calculateAge = function(dob) {
var days = function(date) {
return 31*date.getMonth() + date.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - ( measureDays(now) < measureDays(d));
}
I hope that helps :D
here is a simple way of calculating age:
//dob date dd/mm/yy
var d = 01/01/1990
//today
//date today string format
var today = new Date(); // i.e wed 04 may 2016 15:12:09 GMT
//todays year
var todayYear = today.getFullYear();
// today month
var todayMonth = today.getMonth();
//today date
var todayDate = today.getDate();
//dob
//dob parsed as date format
var dob = new Date(d);
// dob year
var dobYear = dob.getFullYear();
// dob month
var dobMonth = dob.getMonth();
//dob date
var dobDate = dob.getDate();
var yearsDiff = todayYear - dobYear ;
var age;
if ( todayMonth < dobMonth )
{
age = yearsDiff - 1;
}
else if ( todayMonth > dobMonth )
{
age = yearsDiff ;
}
else //if today month = dob month
{ if ( todayDate < dobDate )
{
age = yearsDiff - 1;
}
else
{
age = yearsDiff;
}
}
var now = DateTime.Now;
var age = DateTime.Now.Year - dob.Year;
if (now.Month < dob.Month || now.Month == dob.Month && now.Day < dob.Day) age--;
You may use this for age restriction in your form -
function dobvalidator(birthDateString){
strs = birthDateString.split("-");
var dd = strs[0];
var mm = strs[1];
var yy = strs[2];
var d = new Date();
var ds = d.getDate();
var ms = d.getMonth();
var ys = d.getFullYear();
var accepted_age = 18;
var days = ((accepted_age * 12) * 30) + (ms * 30) + ds;
var age = (((ys - yy) * 12) * 30) + ((12 - mm) * 30) + parseInt(30 - dd);
if((days - age) <= '0'){
console.log((days - age));
alert('You are at-least ' + accepted_age);
}else{
console.log((days - age));
alert('You are not at-least ' + accepted_age);
}
}
This is my modification:
function calculate_age(date) {
var today = new Date();
var today_month = today.getMonth() + 1; //STRANGE NUMBERING //January is 0!
var age = today.getYear() - date.getYear();
if ((today_month > date.getMonth() || ((today_month == date.getMonth()) && (today.getDate() < date.getDate())))) {
age--;
}
return age;
};
I believe that sometimes the readability is more important in this case. Unless we are validating 1000s of fields, this should be accurate and fast enough:
function is18orOlder(dateString) {
const dob = new Date(dateString);
const dobPlus18 = new Date(dob.getFullYear() + 18, dob.getMonth(), dob.getDate());
return dobPlus18 .valueOf() <= Date.now();
}
// Testing:
console.log(is18orOlder('01/01/1910')); // true
console.log(is18orOlder('01/01/2050')); // false
// When I'm posting this on 10/02/2020, so:
console.log(is18orOlder('10/08/2002')); // true
console.log(is18orOlder('10/19/2002')) // false
I like this approach instead of using a constant for how many ms are in a year, and later messing with the leap years, etc. Just letting the built-in Date to do the job.
Update, posting this snippet since one may found it useful. Since I'm enforcing a mask on the input field, to have the format of mm/dd/yyyy and already validating if the date is valid, in my case, this works too to validate 18+ years:
function is18orOlder(dateString) {
const [month, date, year] = value.split('/');
return new Date(+year + 13, +month, +date).valueOf() <= Date.now();
}

Javascript Date string to Age [duplicate]

How can I calculate an age in years, given a birth date of format YYYYMMDD? Is it possible using the Date() function?
I am looking for a better solution than the one I am using now:
var dob = '19800810';
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
alert(age);
Try this.
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;
}
I believe the only thing that looked crude on your code was the substr part.
Fiddle: http://jsfiddle.net/codeandcloud/n33RJ/
I would go for readability:
function _calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Disclaimer: This also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).
Instead I would recommend using a library for this, if precision is very important. Also #Naveens post, is probably the most accurate, as it doesn't rely on the time of day.
Important: This answer doesn't provide an 100% accurate answer, it is off by around 10-20 hours depending on the date.
There are no better solutions ( not in these answers anyway ). - naveen
I of course couldn't resist the urge to take up the challenge and make a faster and shorter birthday calculator than the current accepted solution.
The main point for my solution, is that math is fast, so instead of using branching, and the date model javascript provides to calculate a solution we use the wonderful math
The answer looks like this, and runs ~65% faster than naveen's plus it's much shorter:
function calcAge(dateString) {
var birthday = +new Date(dateString);
return ~~((Date.now() - birthday) / (31557600000));
}
The magic number: 31557600000 is 24 * 3600 * 365.25 * 1000
Which is the length of a year, the length of a year is 365 days and 6 hours which is 0.25 day. In the end i floor the result which gives us the final age.
Here is the benchmarks: http://jsperf.com/birthday-calculation
To support OP's data format you can replace +new Date(dateString);
with +new Date(d.substr(0, 4), d.substr(4, 2)-1, d.substr(6, 2));
If you can come up with a better solution please share! :-)
Clean one-liner solution using ES6:
const getAge = birthDate => Math.floor((new Date() - new Date(birthDate).getTime()) / 3.15576e+10)
// today is 2018-06-13
getAge('1994-06-14') // 23
getAge('1994-06-13') // 24
I am using a year of 365.25 days (0.25 because of leap years) which are 3.15576e+10 milliseconds (365.25 * 24 * 60 * 60 * 1000) respectively.
It has a few hours margin so depending on the use case it may not be the best option.
With momentjs:
/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')
Some time ago I made a function with that purpose:
function getAge(birthDate) {
var now = new Date();
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// days since the birthdate
var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
var age = 0;
// iterate the years
for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
}
It takes a Date object as input, so you need to parse the 'YYYYMMDD' formatted date string:
var birthDateStr = '19840831',
parts = birthDateStr.match(/(\d{4})(\d{2})(\d{2})/),
dateObj = new Date(parts[1], parts[2]-1, parts[3]); // months 0-based!
getAge(dateObj); // 26
Here's my solution, just pass in a parseable date:
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
// ageMonth = age.getMonth(); // Accurate calculation of the month part of the age
// ageDay = age.getDate(); // Approximate calculation of the day part of the age
}
Alternate solution, because why not:
function calculateAgeInYears (date) {
var now = new Date();
var current_year = now.getFullYear();
var year_diff = current_year - date.getFullYear();
var birthday_this_year = new Date(current_year, date.getMonth(), date.getDate());
var has_had_birthday_this_year = (now >= birthday_this_year);
return has_had_birthday_this_year
? year_diff
: year_diff - 1;
}
function age()
{
var birthdate = $j('#birthDate').val(); // in "mm/dd/yyyy" format
var senddate = $j('#expireDate').val(); // in "mm/dd/yyyy" format
var x = birthdate.split("/");
var y = senddate.split("/");
var bdays = x[1];
var bmonths = x[0];
var byear = x[2];
//alert(bdays);
var sdays = y[1];
var smonths = y[0];
var syear = y[2];
//alert(sdays);
if(sdays < bdays)
{
sdays = parseInt(sdays) + 30;
smonths = parseInt(smonths) - 1;
//alert(sdays);
var fdays = sdays - bdays;
//alert(fdays);
}
else{
var fdays = sdays - bdays;
}
if(smonths < bmonths)
{
smonths = parseInt(smonths) + 12;
syear = syear - 1;
var fmonths = smonths - bmonths;
}
else
{
var fmonths = smonths - bmonths;
}
var fyear = syear - byear;
document.getElementById('patientAge').value = fyear+' years '+fmonths+' months '+fdays+' days';
}
I think that could be simply like that:
function age(dateString){
let birth = new Date(dateString);
let now = new Date();
let beforeBirth = ((() => {birth.setDate(now.getDate());birth.setMonth(now.getMonth()); return birth.getTime()})() < birth.getTime()) ? 0 : 1;
return now.getFullYear() - birth.getFullYear() - beforeBirth;
}
age('09/20/1981');
//35
Works also with a timestamp
age(403501000000)
//34
That's the most elegant way for me:
const getAge = (birthDateString) => {
const today = new Date();
const birthDate = new Date(birthDateString);
const yearsDifference = today.getFullYear() - birthDate.getFullYear();
if (
today.getMonth() < birthDate.getMonth() ||
(today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
) {
return yearsDifference - 1;
}
return yearsDifference;
};
console.log(getAge('2018-03-12'));
This question is over 10 years old an nobody has addressed the prompt that they already have the birth date in YYYYMMDD format?
If you have a past date and the current date both in YYYYMMDD format, you can very quickly calculate the number of years between them like this:
var pastDate = '20101030';
var currentDate = '20210622';
var years = Math.floor( ( currentDate - pastDate ) * 0.0001 );
// 10 (10.9592)
You can get the current date formatted as YYYYMMDD like this:
var now = new Date();
var currentDate = [
now.getFullYear(),
('0' + (now.getMonth() + 1) ).slice(-2),
('0' + now.getDate() ).slice(-2),
].join('');
To test whether the birthday already passed or not, I define a helper function Date.prototype.getDoY, which effectively returns the day number of the year. The rest is pretty self-explanatory.
Date.prototype.getDoY = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.floor(((this - onejan) / 86400000) + 1);
};
function getAge(birthDate) {
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
var now = new Date(),
age = now.getFullYear() - birthDate.getFullYear(),
doyNow = now.getDoY(),
doyBirth = birthDate.getDoY();
// normalize day-of-year in leap years
if (isLeap(now.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyNow--;
if (isLeap(birthDate.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyBirth--;
if (doyNow <= doyBirth)
age--; // birthday not yet passed this year, so -1
return age;
};
var myBirth = new Date(2001, 6, 4);
console.log(getAge(myBirth));
I just had to write this function for myself - the accepted answer is fairly good but IMO could use some cleanup. This takes a unix timestamp for dob because that was my requirement but could be quickly adapted to use a string:
var getAge = function(dob) {
var measureDays = function(dateObj) {
return 31*dateObj.getMonth()+dateObj.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - (measureDays(now) < measureDays(d));
}
Notice I've used a flat value of 31 in my measureDays function. All the calculation cares about is that the "day-of-year" be a monotonically increasing measure of the timestamp.
If using a javascript timestamp or string, obviously you'll want to remove the factor of 1000.
function getAge(dateString) {
var dates = dateString.split("-");
var d = new Date();
var userday = dates[0];
var usermonth = dates[1];
var useryear = dates[2];
var curday = d.getDate();
var curmonth = d.getMonth()+1;
var curyear = d.getFullYear();
var age = curyear - useryear;
if((curmonth < usermonth) || ( (curmonth == usermonth) && curday < userday )){
age--;
}
return age;
}
To get the age when european date has entered:
getAge('16-03-1989')
I've checked the examples showed before and they didn't worked in all cases, and because of this i made a script of my own. I tested this, and it works perfectly.
function getAge(birth) {
var today = new Date();
var curr_date = today.getDate();
var curr_month = today.getMonth() + 1;
var curr_year = today.getFullYear();
var pieces = birth.split('/');
var birth_date = pieces[0];
var birth_month = pieces[1];
var birth_year = pieces[2];
if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year-birth_year);
if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year-birth_year-1);
if (curr_month > birth_month) return parseInt(curr_year-birth_year);
if (curr_month < birth_month) return parseInt(curr_year-birth_year-1);
}
var age = getAge('18/01/2011');
alert(age);
Get the age (years, months and days) from the date of birth with javascript
Function calcularEdad (years, months and days)
function calcularEdad(fecha) {
// Si la fecha es correcta, calculamos la edad
if (typeof fecha != "string" && fecha && esNumero(fecha.getTime())) {
fecha = formatDate(fecha, "yyyy-MM-dd");
}
var values = fecha.split("-");
var dia = values[2];
var mes = values[1];
var ano = values[0];
// cogemos los valores actuales
var fecha_hoy = new Date();
var ahora_ano = fecha_hoy.getYear();
var ahora_mes = fecha_hoy.getMonth() + 1;
var ahora_dia = fecha_hoy.getDate();
// realizamos el calculo
var edad = (ahora_ano + 1900) - ano;
if (ahora_mes < mes) {
edad--;
}
if ((mes == ahora_mes) && (ahora_dia < dia)) {
edad--;
}
if (edad > 1900) {
edad -= 1900;
}
// calculamos los meses
var meses = 0;
if (ahora_mes > mes && dia > ahora_dia)
meses = ahora_mes - mes - 1;
else if (ahora_mes > mes)
meses = ahora_mes - mes
if (ahora_mes < mes && dia < ahora_dia)
meses = 12 - (mes - ahora_mes);
else if (ahora_mes < mes)
meses = 12 - (mes - ahora_mes + 1);
if (ahora_mes == mes && dia > ahora_dia)
meses = 11;
// calculamos los dias
var dias = 0;
if (ahora_dia > dia)
dias = ahora_dia - dia;
if (ahora_dia < dia) {
ultimoDiaMes = new Date(ahora_ano, ahora_mes - 1, 0);
dias = ultimoDiaMes.getDate() - (dia - ahora_dia);
}
return edad + " años, " + meses + " meses y " + dias + " días";
}
Function esNumero
function esNumero(strNumber) {
if (strNumber == null) return false;
if (strNumber == undefined) return false;
if (typeof strNumber === "number" && !isNaN(strNumber)) return true;
if (strNumber == "") return false;
if (strNumber === "") return false;
var psInt, psFloat;
psInt = parseInt(strNumber);
psFloat = parseFloat(strNumber);
return !isNaN(strNumber) && !isNaN(psFloat);
}
One more possible solution with moment.js:
var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5
I am a bit too late but I found this to be the simplest way to calculate a birth date.
Hopefully this will help.
function init() {
writeYears("myage", 0, Age());
}
function Age() {
var birthday = new Date(1997, 02, 01), //Year, month-1 , day.
today = new Date(),
one_year = 1000 * 60 * 60 * 24 * 365;
return Math.floor((today.getTime() - birthday.getTime()) / one_year);
}
function writeYears(id, current, maximum) {
document.getElementById(id).innerHTML = current;
if (current < maximum) {
setTimeout(function() {
writeYears(id, ++current, maximum);
}, Math.sin(current / maximum) * 200);
}
}
init()
<span id="myage"></span>
Works perfect for me, guys.
getAge(birthday) {
const millis = Date.now() - Date.parse(birthday);
return new Date(millis).getFullYear() - 1970;
}
I know this is a very old thread but I wanted to put in this implementation that I wrote for finding the age which I believe is much more accurate.
var getAge = function(year,month,date){
var today = new Date();
var dob = new Date();
dob.setFullYear(year);
dob.setMonth(month-1);
dob.setDate(date);
var timeDiff = today.valueOf() - dob.valueOf();
var milliInDay = 24*60*60*1000;
var noOfDays = timeDiff / milliInDay;
var daysInYear = 365.242;
return ( noOfDays / daysInYear ) ;
}
Ofcourse you could adapt this to fit in other formats of getting the parameters. Hope this helps someone looking for a better solution.
I used this approach using logic instead of math.
It's precise and quick.
The parameters are the year, month and day of the person's birthday.
It returns the person's age as an integer.
function calculateAge(year, month, day) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getUTCMonth() + 1;
var currentDay = currentDate.getUTCDate();
// You need to treat the cases where the year, month or day hasn't arrived yet.
var age = currentYear - year;
if (currentMonth > month) {
return age;
} else {
if (currentDay >= day) {
return age;
} else {
age--;
return age;
}
}
}
Adopting from naveen's and original OP's posts I ended up with a reusable method stub that accepts both strings and / or JS Date objects.
I named it gregorianAge() because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.
/**
* Calculates human age in years given a birth day. Optionally ageAtDate
* can be provided to calculate age at a specific date
*
* #param string|Date Object birthDate
* #param string|Date Object ageAtDate optional
* #returns integer Age between birthday and a given date or today
*/
function gregorianAge(birthDate, ageAtDate) {
// convert birthDate to date object if already not
if (Object.prototype.toString.call(birthDate) !== '[object Date]')
birthDate = new Date(birthDate);
// use today's date if ageAtDate is not provided
if (typeof ageAtDate == "undefined")
ageAtDate = new Date();
// convert ageAtDate to date object if already not
else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')
ageAtDate = new Date(ageAtDate);
// if conversion to date object fails return null
if (ageAtDate == null || birthDate == null)
return null;
var _m = ageAtDate.getMonth() - birthDate.getMonth();
// answer: ageAt year minus birth year less one (1) if month and day of
// ageAt year is before month and day of birth year
return (ageAtDate.getFullYear()) - birthDate.getFullYear()
- ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate())) ? 1 : 0)
}
// Below is for the attached snippet
function showAge() {
$('#age').text(gregorianAge($('#dob').val()))
}
$(function() {
$(".datepicker").datepicker();
showAge();
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
DOB:
<input name="dob" value="12/31/1970" id="dob" class="datepicker" onChange="showAge()" /> AGE: <span id="age"><span>
Two more options:
// Int Age to Date as string YYY-mm-dd
function age_to_date(age)
{
try {
var d = new Date();
var new_d = '';
d.setFullYear(d.getFullYear() - Math.abs(age));
new_d = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();
return new_d;
} catch(err) {
console.log(err.message);
}
}
// Date string (YYY-mm-dd) to Int age (years old)
function date_to_age(date)
{
try {
var today = new Date();
var d = new Date(date);
var year = today.getFullYear() - d.getFullYear();
var month = today.getMonth() - d.getMonth();
var day = today.getDate() - d.getDate();
var carry = 0;
if (year < 0)
return 0;
if (month <= 0 && day <= 0)
carry -= 1;
var age = parseInt(year);
age += carry;
return Math.abs(age);
} catch(err) {
console.log(err.message);
}
}
I've did some updated to one previous answer.
var calculateAge = function(dob) {
var days = function(date) {
return 31*date.getMonth() + date.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - ( measureDays(now) < measureDays(d));
}
I hope that helps :D
here is a simple way of calculating age:
//dob date dd/mm/yy
var d = 01/01/1990
//today
//date today string format
var today = new Date(); // i.e wed 04 may 2016 15:12:09 GMT
//todays year
var todayYear = today.getFullYear();
// today month
var todayMonth = today.getMonth();
//today date
var todayDate = today.getDate();
//dob
//dob parsed as date format
var dob = new Date(d);
// dob year
var dobYear = dob.getFullYear();
// dob month
var dobMonth = dob.getMonth();
//dob date
var dobDate = dob.getDate();
var yearsDiff = todayYear - dobYear ;
var age;
if ( todayMonth < dobMonth )
{
age = yearsDiff - 1;
}
else if ( todayMonth > dobMonth )
{
age = yearsDiff ;
}
else //if today month = dob month
{ if ( todayDate < dobDate )
{
age = yearsDiff - 1;
}
else
{
age = yearsDiff;
}
}
var now = DateTime.Now;
var age = DateTime.Now.Year - dob.Year;
if (now.Month < dob.Month || now.Month == dob.Month && now.Day < dob.Day) age--;
You may use this for age restriction in your form -
function dobvalidator(birthDateString){
strs = birthDateString.split("-");
var dd = strs[0];
var mm = strs[1];
var yy = strs[2];
var d = new Date();
var ds = d.getDate();
var ms = d.getMonth();
var ys = d.getFullYear();
var accepted_age = 18;
var days = ((accepted_age * 12) * 30) + (ms * 30) + ds;
var age = (((ys - yy) * 12) * 30) + ((12 - mm) * 30) + parseInt(30 - dd);
if((days - age) <= '0'){
console.log((days - age));
alert('You are at-least ' + accepted_age);
}else{
console.log((days - age));
alert('You are not at-least ' + accepted_age);
}
}
This is my modification:
function calculate_age(date) {
var today = new Date();
var today_month = today.getMonth() + 1; //STRANGE NUMBERING //January is 0!
var age = today.getYear() - date.getYear();
if ((today_month > date.getMonth() || ((today_month == date.getMonth()) && (today.getDate() < date.getDate())))) {
age--;
}
return age;
};
I believe that sometimes the readability is more important in this case. Unless we are validating 1000s of fields, this should be accurate and fast enough:
function is18orOlder(dateString) {
const dob = new Date(dateString);
const dobPlus18 = new Date(dob.getFullYear() + 18, dob.getMonth(), dob.getDate());
return dobPlus18 .valueOf() <= Date.now();
}
// Testing:
console.log(is18orOlder('01/01/1910')); // true
console.log(is18orOlder('01/01/2050')); // false
// When I'm posting this on 10/02/2020, so:
console.log(is18orOlder('10/08/2002')); // true
console.log(is18orOlder('10/19/2002')) // false
I like this approach instead of using a constant for how many ms are in a year, and later messing with the leap years, etc. Just letting the built-in Date to do the job.
Update, posting this snippet since one may found it useful. Since I'm enforcing a mask on the input field, to have the format of mm/dd/yyyy and already validating if the date is valid, in my case, this works too to validate 18+ years:
function is18orOlder(dateString) {
const [month, date, year] = value.split('/');
return new Date(+year + 13, +month, +date).valueOf() <= Date.now();
}

Categories