391

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);
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Francisc
  • 77,430
  • 63
  • 180
  • 276
  • Please mind your formatting, don't do it the way you did; just indent your code with 4 spaces using the code (010101) button or Ctrl-K. – Marcel Korpel Oct 30 '10 at 19:28
  • I did but it fails to work on IE9 Beta so I had to do it by hand. – Francisc Oct 31 '10 at 00:04
  • 4
    Your original solution is better, at calculating the age, than the current answers. Júlio Santos' answer is essentially the same thing. The other answers give inaccurate results under many conditions, and may be less straightforward or less efficient. – Brock Adams May 08 '11 at 06:14
  • Thank you Brock. I was hoping there was a more elegant way of doing this than that which seems a bit crude. – Francisc May 09 '11 at 14:24
  • 4
    @Francisc, it is crude, but it's what the `Date` object would have to do if it encapsulated it. People could write books about the suckiness of JS's `Date` handling. ... If you can live with sometimes being off by a day, then the approximation: `AgeInYears = Math.floor ( (now_Date - DOB_Date) / 31556952000 )` is about as simple as you can get. – Brock Adams May 09 '11 at 23:19
  • I can't live with that. Haha. You should make an answer of your initial comment as it seems the currently correct one isn't 100% precise and could lead to poor implementations of readers. – Francisc May 10 '11 at 22:58
  • here a good performance test for the mentioned possibilities below: http://jsben.ch/#/Xsg3o – EscapeNetscape Oct 25 '16 at 08:17
  • Sorry, as this is an old post, but still matches on Google. I wanted to note you need to add a "1" to the getMonth(), as getMonth for Jan returns 0 – Vinnie Amir Mar 15 '22 at 01:30

48 Answers48

667

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/

naveen
  • 53,448
  • 46
  • 161
  • 251
  • Can you give a usage example? I couldn't get it to work without modifying the function to take 3 separate arguments, such as: getAge(y,m,d). For example: http://jsbin.com/ehaqiw/1/edit – edt Apr 15 '13 at 04:20
  • Like many others, this thinks that 2000-02-29 to 2001-02-28 is zero years, when it most likely should be 1 (since to 2001-03-01 should be 1 year 1 day). – RobG Mar 21 '14 at 14:54
  • 4
    @RobG: when leaplings 'celebrate' (the common answer to that question only actually seems to be: 'the weekend closest to the actual date') their birth-day **differs** based on context including: geographical region (simple English: where you live), LAW (don't underestimate that one), religion and personal preference (including group-behavior): Some reason: "I'm born in February", others reason: "I'm born the day after 28th of February" (which is most commonly March 1th) http://en.wikipedia.org/wiki/February_29 For all the above this algo is correct IF March 1th is the leapyear result one needs – GitaarLAB Jan 09 '15 at 06:17
  • @GitaarLAB—but common sense should prevail. Is 31 May plus one month 1 July or 30 June? Is 31 January plus one month 3 March (or 2 March in a leap year)? The same rules should apply to 28/29 February. Of course different administrations and rule makers have different interpretations, answers should at least highlight the issues. – RobG Mar 17 '16 at 09:19
  • 4
    @RobG: The cesspit of 'plus x month(s)' is irrelevant to the human notion of age in years. The common human notion is that the age(InYears)-counter increases every day (disregarding time) when the calendar has the same month# and day# (compared to start-date): so that 2000-02-28 to 2001-02-27 = 0 years and 2000-02-28 to 2001-02-28 = 1 year. Extending that 'common sense' to leaplings: 2000-02-29 (the day *after* 2000-02-28) to 2001-02-28 = *zero years*. My comment merely stated that the answered algo always gives the 'correct' *human answer* IF one expects/agrees to this logic for leaplings. – GitaarLAB Mar 17 '16 at 11:42
  • @GitaarLAB—you can argue your point of view all you like, the fact is that different jurisdictions adopt different views. I'm not saying I'm definitively correct, only that it is ambiguous and that both cases should be considered. Adding months is just an example of how different points of view can arrive at different results with legitimate claims for correctness. If 29 February plus one year is 1 March, then the same logic says 31 February plus one month is 1 March, or maybe 2 or 3 March, and 31 May plus one month is 1 July. – RobG Mar 17 '16 at 12:25
  • 3
    @RobG: I never said I or the answer was *universally* correct(TM). I included notion of contexts/jurisdictions/views. Both my comments clearly include an uppercase *IF* (towards the handling of the exception leaplings). In fact, my first comment stated exactly what I meant to say and never included any judgment regarding right or wrong. In effect my comments clarify what and what not to expect (and why) from this answer (as you call it 'highlight the issues'). Ps: 31 February ?!? – GitaarLAB Mar 17 '16 at 13:30
  • Ha, yes, 31 January plus one month. :-) – RobG Mar 17 '16 at 14:28
  • This one was the most accurate, trying multiple answers in my personal testing. – Phillip Quinlan May 28 '18 at 22:17
  • 1
    @Dr.G: For me, its 63. http://jsfiddle.net/codeandcloud/o86au3dn/ Please double-check your code – naveen Dec 01 '21 at 05:16
321

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.


André Snede
  • 9,899
  • 7
  • 43
  • 67
  • 3
    This returns 0 years for dates like 2000-02-29 to 2001-02-28 when it probably should return 1. – RobG Mar 21 '14 at 14:13
  • I commented on Naveen's answer too. It does the same thing, as does every other answer I tried—except mine of course. :-) – RobG Mar 21 '14 at 22:01
  • 20
    @RobG I don't think a full year technically has passed from 2000-02-29 to 2001-02-28, making your answer invalid. It wouldn't make sense, 2000-02-28 to 2001-02-28 is a year, so 2000-02-29 to 2001-02-28, must be less than a year. – André Snede Mar 22 '14 at 00:04
  • There's something else going on too, it thinks 2012-02-28 to 2013-02-27 is one year. – RobG Mar 23 '14 at 23:14
  • @RobG, what part of "not precise", is it that you are having a hard time to comprehend? – André Snede Mar 24 '14 at 07:12
  • 4
    You didn't elaborate on what "not precise" means, I thought additional information might be helpful. You might consider fixing the issues or deleting the answer. – RobG Mar 24 '14 at 08:40
  • 4
    @RobG Actually I did. I also pointed to a better solution than my own. My solution solves the problem in an easy to read fashion, with minor precision issues, but within the bounds of its purpose. – André Snede Mar 24 '14 at 09:30
  • @vee It needs a Date as input. – André Snede Mar 24 '14 at 20:47
  • @vee Create a question for it on the site. – André Snede Mar 24 '14 at 20:52
  • 1
    Lovely answer @AndréSnedeHansen and fast too, since you don't have that crazy division as is present in my answer ;-) +1 for readability and speed. – Kristoffer Dorph Sep 17 '14 at 14:03
  • @KristofferDorph Thanks, I appreciate that :) Although naveens answer is faster, and more precise. Mine is more of a readable hack. – André Snede Sep 17 '14 at 14:09
  • This does not work with the following DOB 24/02/2007. On todays date (03/02/2015) it thinks the age is 8, where as it is actually 7. – Bex Feb 03 '15 at 13:07
  • @Bex It returns 7, are you remembering that months in javascript Date obj is zero based, and that you have to do: `_calculateAge(new Date(2007, 01, 24))` ? – André Snede Feb 03 '15 at 13:16
  • 1
    @AndréSnedeHansen possibly not. Thank you, I shall check! – Bex Feb 04 '15 at 14:56
  • @AndréSnedeHansen: the leading 0 in `01` for February is not actually needed. Regarding precision: since you use UTC time, there should be no problems with DST at least. And if you zeroed the birthday's time - `setUTCHours(0, 0, 0, 0)` - and used the current date at 24:00:00.000, shouldn't that solve unexpected results like 0 years after 1 perceived year? This actually returns 1, unlike RobG told: `new Date(Date.UTC(2001, 1, 28) - Date.UTC(2000, 1, 29)).getUTCFullYear() - 1970` – CodeManX Sep 01 '15 at 21:34
  • This doesn't give a age in years as intended based on the snippet of OP – nazim Feb 09 '16 at 05:48
  • @BruceLim Nice explanation, I really have something to go on here. – André Snede Mar 31 '16 at 06:15
  • Sorry I had to move onto finding a working solution. Tt would show 18 and 17 at different times of the days. ie. new Date('3/31/1998') -- shows 18 but new Date('3/31/1998 20:00:00') would show 17. Didn't really have time to dig into the exact but my guess is using timestamp to track the time passed. – Bruce Lim Mar 31 '16 at 21:22
  • @BruceLim Jep, I am aware of that issue, as I state in my answer, naveens post is the better solution to this. – André Snede Mar 31 '16 at 22:26
  • @BruceLim why the answer is wrong? what is your explanation about that ? – Hristo Eftimov Aug 11 '16 at 10:30
  • The link is dead now – Johnn5er Aug 19 '16 at 11:20
  • The jsperf link works fine for me today. I would like to see naveen's answer added to the comparisons. – Codes with Hammer Oct 31 '16 at 13:01
  • @CodeswithHammer Naveens answer, is the first test. – André Snede Oct 31 '16 at 13:19
  • @AndréSnedeKock: Oh, so it is. Thanks. (I _thought_ I had compared the two and found them different.) – Codes with Hammer Oct 31 '16 at 13:33
  • This is a bad answer because it doesn't issue a caveat in the answer that it's potentially inaccurate. It may be close enough for many cases, but it should come with a warning - if there were a warning I wouldn't have downvoted it, but as it is I tried using this code and it reports the wrong age for someone whose birthday is tomorrow. – Matt Browne Nov 11 '16 at 14:02
  • @MattBrowne If your birthday is tomorrow, you are not that one year older yet. This answers the question perfectly. If it doesn't answer your specific requirement, create a new question. – André Snede Nov 11 '16 at 14:56
  • @AndréSnedeKock I looked into it further and it can definitely still return the wrong answer, depending on the time of day of the birthdate object you pass in. Even if you call `setUTCHours(0,0,0,0)` on the birthdate prior to passing it to this function, it can still give the wrong result due to timezone differences. Today is Nov. 11 2016 and if I pass in Nov. 12 2006 as the birthdate, it returns 10 but it should be returning 9. – Matt Browne Nov 11 '16 at 17:37
  • I suggest modifying the first part of the function as follows: `var today = new Date(); today.setUTCHours(0,0,0,0); var ageDifMs = today.getTime() - birthday.getTime();` – Matt Browne Nov 11 '16 at 17:38
  • @MattBrowne Yes Matt, that has already been established earlier in the comments. Daylight savings can also affect the result And as I have said before, Naveens answer, does not have the issues that this one has. – André Snede Nov 11 '16 at 18:09
  • 1
    Thank you for editing the question to mention that. I think it will help others. – Matt Browne Nov 11 '16 at 18:20
  • @MattBrowne ofcourse :) This has been brought up a few times, so it must be because it is a valid concern, so it has to be addressed. – André Snede Nov 11 '16 at 18:32
  • @AndréSnedeKock Maybe useful to also check if the Date is before todays Date because passing a future date will result in an age as well – Bernhard Dec 19 '16 at 15:07
  • @Bernhard true, but that is not part of the question, and therefor not part of the answer :) I'm confident that anyone using this code, can make this alteration themselfs. – André Snede Dec 20 '16 at 07:15
  • Here's a one line version of this incase anyone wants it: `new Date(new Date() - new Date(birthday)).getFullYear() - 1970` – maxpelic Aug 05 '19 at 16:34
  • @maxpelic You are aware that you are not making anything faster by condensing it into one line? All you did was make it harder to understand, and that is hardly a metric worth going for. – André Snede Aug 17 '19 at 15:57
  • why 1970 is used? @AndréSnedeKock – Christine Shaji Jan 29 '20 at 13:58
  • @ChristineShaji it is the epoch used in Javascript. – André Snede Feb 05 '20 at 15:47
  • Oh alright.. Thanks for the information. @AndréSnedeKock – Christine Shaji Feb 13 '20 at 09:58
  • The closer birthdate gets to now, the closer the age diff gets to 1970. So if the birthdate is in the future, age diff is negative. The Math.abs() disguises people that aren't born yet with a valid positive age. –  Oct 19 '20 at 09:58
  • Link is invalid – Abdulbosid Mar 19 '21 at 13:47
  • This doesn't work when the given birthday is today, it's not adding a year to the age.... – benshabatnoam Jun 23 '23 at 08:00
84

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! :-)

Kristoffer Dorph
  • 1,233
  • 10
  • 18
  • That's a pretty cool solution. The only problem I see with it is the `dateString` argument just be just right for the Date() constructor to parse it correctly. For example, taking the `YYYYMMDD` format I gave in the question, it will fail. – Francisc Mar 21 '13 at 21:03
  • That is true, just added a comment about that :-) – Kristoffer Dorph Mar 21 '13 at 22:27
  • 25
    This answer has a bug in it. Set your clock to 12:01am. At 12:01am, if you calcAge('2012-03-27') (today's date) you will get an answer of zero, even though it should equal 1. This bug exists for the entire 12:00am hour. This is due to the incorrect statement that a year has 365.25 days in it. It does not. We are dealing with calendar years, not the length of the Earth's orbit (which is more accurately 365.256363 days). A year has 365 days, except a leap year which has 366 days. Besides that, performance on something like this is meaningless. Maintainability is far more important. – Eric Brandel Mar 27 '13 at 17:57
  • Thank you for pointing this out! It seems my solution is indeed off by some hours depending on the date. The reason for the .25 days is to account for leap years, since we have one every 4 years, and if you floor the result, you would have accounted for this offset (365.242 days is the average length of a Gregorian year). Another problem with my code is that there's actually no leap year every 100 year (except every 400). – Kristoffer Dorph Mar 27 '13 at 20:18
  • 1
    Thanks for your solution Kristoffer. Can i ask what the +new does compared to just new, and also the two tilde's (~) in the return? – Frank Jensen May 30 '13 at 09:10
  • 1
    @FrankJensen Hi Frank, i was curious too and found this answer: [double tilde converts float to integer](http://stackoverflow.com/questions/4055633/what-does-do-in-javascript#4055675) Greetings – Stano Jun 11 '13 at 16:19
  • 1
    @FrankJensen essentially the tilde inverts the number (the binary value) whilst converting float to integer (floored), hence, two tilde gives you the rounded number. The + in front of new Date() converts the object to the integer representation of the date object, this can also be used with strings of numbers for instance +'21' === 21 – Kristoffer Dorph Jun 12 '13 at 13:46
  • `~~((Date.now() - birthday) / (31557600000))` is not supported in IE8.0 `Object doesn't support this property or method` –  Aug 05 '13 at 13:19
  • As noted in the comment this is not 100% but if the dates were both parsed from strings that is more than acceptable – Eric Feb 14 '14 at 19:54
  • this is really age, not named age, when we deal with health management, we use this is more righter than the named age. – defend orca Aug 11 '20 at 15:31
  • @Francisc try something like: ```const [ Y1, Y2, Y3, Y4, M1, M2, D1, D2 ] = `${YYYYMMDD}`.split(''); const reformatted = `${M1}${M2}/${D1}${D2}/${Y1}${Y2}${Y3}${Y4}`; // MM/DD/YYYY ```. That's a valid format for JS Dates. (You can also use String.prototype.slice instead of split)... `'19991231'.slice(-2) == DD`. – Cody Dec 08 '22 at 21:45
83

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.

Lucas Janon
  • 1,502
  • 1
  • 15
  • 18
  • 2
    Pretty damn neat - could you elaborate what the 3.15576e+10 means? – leonheess Jul 15 '19 at 12:57
  • 2
    Yes, it would be good to add the following line before the function: `const yearInMs = 3.15576e+10 // Using a year of 365.25 days (because leap years)` – Lucas Janon Jul 15 '19 at 21:24
  • 3
    Works well, but has an error margin of hours. Users turning `18` tommorow are actually 18 `today`. I know I'm not supposed to mention a library but `Day.js` worked like magic. – Dev Yego Nov 08 '20 at 18:37
  • const NUMBER_OF_MILI_SECONDS_IN_YEAR = 31536000000; return Math.floor( (CurrentDate - BirthDay.getTime()) / NUMBER_OF_MILI_SECONDS_IN_YEAR ); – Anas Alpure Jan 15 '22 at 17:53
69

With momentjs:

/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')
Vitor Tyburski
  • 1,062
  • 13
  • 17
  • 4
    @RicardoPontual this requires momentjs, so can't be the best answer. – itzmukeshy7 Jul 11 '17 at 10:57
  • 22
    @itzmukeshy7 indeed, for an answer to be the best one, it should at least require jQuery ;) – thomaux Oct 02 '17 at 13:53
  • @thomaux It totally depends on the development environment! – itzmukeshy7 Oct 02 '17 at 13:56
  • @itzmukeshy7 relax, it's a joke ;) see: https://meta.stackexchange.com/a/19492/173875 – thomaux Oct 02 '17 at 14:04
  • 3
    @thomaux I knew that it is a joke ;) – itzmukeshy7 Oct 02 '17 at 14:07
  • @itzmukeshy7 that link made my day :-D – Dev Yego Nov 07 '20 at 09:21
  • To get years and months e.g. '15 years and 11 months old', you can use Moment.js like so: `let dateOfBirthIso8601DateString = '2006-11-14';` `let years = moment().diff(dateOfBirthIso8601DateString, 'years');` `// Get time in full months between now and when they had their last birthday` `let mostRecentBirthdayMoment = moment(dateOfBirthIso8601DateString).add(years, 'years');` `let fullMonths = moment().diff(mostRecentBirthdayMoment, 'months');` `return `${years}, ${fullMonths} old`; // returns '15 years, 11 months old'` – Dom Eden Nov 14 '22 at 12:59
15

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
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • Ah yes, I missed the leap year. Thank you. – Francisc Oct 30 '10 at 19:04
  • 1
    This gives invalid values for select date combinations! For example, if the `birthDate` is *Jan 5th, 1980*, and the current date is *Jan 4th, 2005*, then the function will erroneously report `age` as 25... The correct value being 24. – Brock Adams May 08 '11 at 05:09
  • @BrockAdams Why is this? I am having this problem at the moment. Thanks. – Jack H Dec 04 '11 at 19:16
  • @VisionIncision, because it does not handle edge conditions properly. Believe it or not, the code from the question is the best approach -- although it looks like one of the later answers might have repackaged it more suitably. – Brock Adams Dec 04 '11 at 20:22
  • CMS Hi :-) I wrote this question (http://stackoverflow.com/questions/16435981/age-leap-year-calculation-in-javascript?noredirect=1#comment23573057_16435981) and I was told that if i want 100% accurate answer i should check every year - if it is a leap year , and then calc the last fraction. (see Guffa's answer). Your function (part of it) **does that**. but how can I use it to calc the age 100% accurate ? the DOB rarely begins at 1/1/yyyy..... so how can i use your func to calc the exact age ? – Royi Namir May 11 '13 at 08:48
  • @CMS can you please answer my last comment ? any way I asked a question here http://stackoverflow.com/questions/16435981/age-leap-year-calculation-in-javascript – Royi Namir May 14 '13 at 13:41
12

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
}
Kinergy
  • 325
  • 3
  • 9
11

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;
}
Josh
  • 716
  • 7
  • 7
7

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('');
cr0ybot
  • 3,960
  • 2
  • 20
  • 22
6
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';
}
Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
Sarwar
  • 61
  • 1
6

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
romuleald
  • 1,406
  • 16
  • 31
  • This code will calculate a person having the same age all year. In your example, if today was '09/19/2018' the code would give 37, but the age (the day before the birthday) would be 36... – Steve Goossens Apr 18 '18 at 22:48
6

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();

    const isBeforeBirthday =
        today.getMonth() < birthDate.getMonth() ||
        (today.getMonth() === birthDate.getMonth() &&
            today.getDate() < birthDate.getDate());

    return isBeforeBirthday ? yearsDifference - 1 : yearsDifference;
};

console.log(getAge("2018-03-12"));
Chris Dąbrowski
  • 1,902
  • 1
  • 12
  • 12
5

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.

5

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));
Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
  • This gives inaccurate results in leap-years, for birthdays after Feb 28th. It ages such people by 1 day. EG: for DoB = *2001/07/04*, this function will return 7 years, on *2008/07/03*. – Brock Adams May 08 '11 at 05:56
  • @Brock: Thanks. If I'm not mistaken, I've corrected this erroneous behaviour. – Marcel Korpel May 09 '11 at 19:55
  • Yes, I think you might have (haven't rigorously tested, just analyzed). But, notice that the new solution is no simpler and no more elegant than the OP's solution (not counting that this one is properly encapsulated in a function). ... The OP's solution is easier to understand (thus to audit, to test or to modify). Sometimes simple and straightforward is best, IMO. – Brock Adams May 09 '11 at 23:33
  • @Brock: I fully agree: I have to think about what this function does and that's never a good thing. – Marcel Korpel May 10 '11 at 08:00
  • Shouldn't "if (doyNow < doyBirth)" be "if (doyNow <= doyBirth)" ? In all my tests, the day has been off by one and that fixed it. – Ted Kulp Jul 25 '11 at 16:53
4
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')
Martijn van Hoof
  • 740
  • 10
  • 28
  • Thanks for your suggestion at http://stackoverflow.com/a/13367162/1055987 good catch. – JFK Apr 05 '13 at 07:33
2

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);
paulinho
  • 146
  • 8
  • Should 2000-02-29 to 2001-02-28 be one year? If so, then the above isn't perfect. :-) – RobG Mar 21 '14 at 15:16
2

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);
}
Angeldev
  • 164
  • 1
  • 4
2

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
Michael Yurin
  • 1,021
  • 14
  • 18
2

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Mishovski
  • 43
  • 7
  • I like it a lot, upvoted. It's different and it works great. –  Dec 25 '20 at 08:23
  • I made you a snippet. Removed the jQuery and the irrelevant captcha. The calculation is off. If I enter tomorrow's date last year, I still get age=1 – mplungjan Feb 16 '21 at 08:02
1

Works perfect for me, guys.

getAge(birthday) {
    const millis = Date.now() - Date.parse(birthday);
    return new Date(millis).getFullYear() - 1970;
}
20 fps
  • 342
  • 5
  • 18
  • I tried this today the 16th of Feb 2020 with tomorrow's date last year `console.log(getAge("2020-02-17"))` and it returns 1 – mplungjan Feb 16 '21 at 07:56
  • Works fine to me, there is probably a timezone difference linked to the Date object. If you need accurate age, use DayJs or Moment with the correct timezone configuration. – Guillaume F. Feb 02 '22 at 04:30
1

Short and accurate (but not super readable):

let age = (bdate, now = new Date(), then = new Date(bdate)) => now.getFullYear() - then.getFullYear() - (now < new Date(now.getFullYear(), then.getMonth(), then.getDate()));
Thomas Frank
  • 1,404
  • 4
  • 10
  • The code doesn't work with format YYYYMMDD, which is the question's requirement. – David Lukas Dec 07 '21 at 20:33
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30523515) – David Lukas Dec 07 '21 at 20:38
  • The code does work with the format YYYYMMDDD, although in saying so I DO expect you to have the knowledge that you can create a date in JS using **new Date("YYYY-MM-DD")**. I am sorry if this was unclear. – Thomas Frank Apr 29 '23 at 23:06
0

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.

ganaraj
  • 26,841
  • 6
  • 63
  • 59
0

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;
            }
        }
    }
Pedro Alvares
  • 479
  • 5
  • 9
0

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>
nazim
  • 1,439
  • 2
  • 16
  • 26
0

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);
    }
}
rsnoopy
  • 26
  • 3
0

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

Fabricio
  • 3,248
  • 2
  • 16
  • 22
0

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;
    }
 }
SSS
  • 300
  • 4
  • 10
0
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--;
DBoi
  • 627
  • 2
  • 17
  • 35
  • It does a simple year difference between now and the year of birth. Then it subtracts a year if today is earlier in the year than the birthday (think about it, your age goes up during the year, on your birthday) – Steve Goossens Apr 18 '18 at 22:52
0

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);
    }
}
IshaniNet
  • 153
  • 10
0

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;
  };
zubroid
  • 121
  • 10
0

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();
}
Constantin
  • 3,655
  • 1
  • 14
  • 23
0

Simple js script

(function calcAge() {
            const birthdate = new Date(2000, 7, 25) // YYYY, MM, DD
            const today = new Date()
            const age = today.getFullYear() - birthdate.getFullYear() -
                (today.getMonth() < birthdate.getMonth() ||
                    (today.getMonth() === birthdate.getMonth() && today.getDate() < birthdate.getDate()))
            return age
        })()
0
/*
    Calculate the Age based on the Date of birth.   FORMAT -"YYYYmmdd"

    @param {String} dateString - date of birth compared to current date
    @return age (years)
*/
function Common_DateTime_GetAge(dateString) 
{ 
    var year = dateString.substring(0,4);
     var month = dateString.substring(4,6);
     var day = dateString.substring(6);
     
    var now = new Date(); 
    var birthdate = new Date(year, month, day); 
    
    var years = now.getFullYear() - birthdate.getFullYear();  //difference
    var months = (now.getMonth()+1) - birthdate.getMonth();   //difference
    var days = now.getDate() - birthdate.getDate();           //difference

    // Check months and day differences to decide when to subtract a year 
    if ((months >= 0 && days > 0)) 
    { 
        years--; 
    } 
    else if ((months > 0 && days <= 0)) 
    { 
        years--; 
    }
    
    return years;           
}
clarksss
  • 281
  • 3
  • 7
0

Using date-fns (momentJS is now a legacy package):

differenceInYears( new Date(),parse('19800810','yyyyMMdd', new Date()) 
yoty66
  • 390
  • 2
  • 12
-1

Here's the simplest, most accurate solution I could come up with:

Date.prototype.getAge = function (date) {
    if (!date) date = new Date();
    return ~~((date.getFullYear() + date.getMonth() / 100
    + date.getDate() / 10000) - (this.getFullYear() + 
    this.getMonth() / 100 + this.getDate() / 10000));
}

And here is a sample that will consider Feb 29 -> Feb 28 a year.

Date.prototype.getAge = function (date) {
    if (!date) date = new Date();
    var feb = (date.getMonth() == 1 || this.getMonth() == 1);
    return ~~((date.getFullYear() + date.getMonth() / 100 + 
        (feb && date.getDate() == 29 ? 28 : date.getDate())
        / 10000) - (this.getFullYear() + this.getMonth() / 100 + 
        (feb && this.getDate() == 29 ? 28 : this.getDate()) 
        / 10000));
}

It even works with negative age!

wizulus
  • 5,653
  • 2
  • 23
  • 40
-1

Yet another solution:

/**
 * Calculate age by birth date.
 *
 * @param int birthYear Year as YYYY.
 * @param int birthMonth Month as number from 1 to 12.
 * @param int birthDay Day as number from 1 to 31.
 * @return int
 */
function getAge(birthYear, birthMonth, birthDay) {
  var today = new Date();
  var birthDate = new Date(birthYear, birthMonth-1, birthDay);
  var age = today.getFullYear() - birthDate.getFullYear();
  var m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}
xexsus
  • 1
-1

see this example you get full year month day information from here

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    var da = today.getDate() - birthDate.getDate();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    if(m<0){
        m +=12;
    }
    if(da<0){
        da +=30;
    }
    return age+" years "+ Math.abs(m) + "months"+ Math.abs(da) + " days";
}
alert('age: ' + getAge("1987/08/31"));    
[http://jsfiddle.net/tapos00/2g70ue5y/][1]
tapos ghosh
  • 2,114
  • 23
  • 37
-1

If you need the age in months (days are approximation):

birthDay=28;
birthMonth=7;
birthYear=1974;

var  today = new Date();
currentDay=today.getUTCDate();
currentMonth=today.getUTCMonth() + 1;
currentYear=today.getFullYear();

//calculate the age in months:
Age = (currentYear-birthYear)*12 + (currentMonth-birthMonth) + (currentDay-birthDay)/30;
-1

Calculate age from date picker

         $('#ContentPlaceHolder1_dob').on('changeDate', function (ev) {
            $(this).datepicker('hide');

            //alert($(this).val());
            var date = formatDate($(this).val()); // ('2010/01/18') to ("1990/4/16"))
            var age = getAge(date);

            $("#ContentPlaceHolder1_age").val(age);
        });


    function formatDate(input) {
        var datePart = input.match(/\d+/g),
        year = datePart[0], // get only two digits
        month = datePart[1], day = datePart[2];
        return day + '/' + month + '/' + year;
    }

    // alert(formatDate('2010/01/18'));


    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;
    }
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87
-1

The below answer is the way to go if the age is just for display purposes (Might not be 100% accurate) but atleast it is easier to wrap your head around

function age(birthdate){
  return Math.floor((new Date().getTime() - new Date(birthdate).getTime()) / 3.154e+10)
}
Malik Bagwala
  • 2,695
  • 7
  • 23
  • 38
-1
let dt = dob;

        let age = '';

        let bY = Number(moment(dt).format('YYYY')); 
        let bM = Number(moment(dt).format('MM')); 
        let bD = Number(moment(dt).format('DD')); 

        let tY = Number(moment().format('YYYY')); 
        let tM = Number(moment().format('MM')); 
        let tD = Number(moment().format('DD')); 


        age += (tY - bY) + ' Y ';

        if (tM < bM) {
            age += (tM - bM + 12) + ' M ';
            tY = tY - 1;
        } else {
            age += (tM - bM) + ' M '
        }

        if (tD < bD) {
            age += (tD - bD + 30) + ' D ';
            tM = tM - 1;
        } else {
            age += (tD - bD) + ' D '
        }
        
        //AGE MONTH DAYS
        console.log(age);
Muhammad Ibrahim
  • 507
  • 9
  • 19
-2

All the answers I tested here (about half) think 2000-02-29 to 2001-02-28 is zero years, when it most likely should be 1 since 2000-02-29 to 2001-03-01 is 1 year and 1 day. Here is a getYearDiff function that fixes that. It only works where d0 < d1:

function getYearDiff(d0, d1) {

    d1 = d1 || new Date();

    var m = d0.getMonth();
    var years = d1.getFullYear() - d0.getFullYear();

    d0.setFullYear(d0.getFullYear() + years);

    if (d0.getMonth() != m) d0.setDate(0);

    return d0 > d1? --years : years;
}
RobG
  • 142,382
  • 31
  • 172
  • 209
  • I don't think a full year technically has passed from 2000-02-29 to 2001-02-28, making your answer invalid. It wouldn't make sense, 2000-02-28 to 2001-02-28 is a year, so 2000-02-29 to 2001-02-28, must be less than a year. – André Snede Mar 22 '14 at 00:07
  • 1
    "Technically"? It is purely an administrative thing, the there are probably as many places that go for 1 March as 28 Feb. So there is need for a choice that no one else thought to do. – RobG Mar 22 '14 at 08:27
  • It's definetely not an "administrative thing", its purely defined in time specifications, which I am not going to dig through. – André Snede Mar 22 '14 at 22:04
  • @AndréSnedeHansen—if you create a Date for 2000-02-29 and add one year using *setDate(getDate + 1)* you'll get 2001-03-01. But that is a choice of the javascript authors based on what Java does, similar to how the default *toString* returns dates in month, day, year order, which is inconsistent with the vast majority of administrative systems. Do some research into how different places treat leap years and durations. – RobG Jan 06 '15 at 06:10
-2

With momentjs "fromNow" method, This allows you to work with formatted date, ie: 03/15/1968

var dob = document.getElementByID("dob"); var age = moment(dob.value).fromNow(true).replace(" years", "");

//fromNow(true) => suffix "ago" is not displayed //but we still have to get rid of "years";

As a prototype version

String.prototype.getAge = function() {
return moment(this.valueOf()).fromNow(true).replace(" years", "");

}

Nicolas Giszpenc
  • 677
  • 6
  • 11
-2

I have a pretty answer although it's not my code. Unfortunately I forgot the original post.

function calculateAge(y, m, d) {
    var _birth = parseInt("" + y + affixZero(m) + affixZero(d));
    var  today = new Date();
    var _today = parseInt("" + today.getFullYear() + affixZero(today.getMonth() + 1) + affixZero(today.getDate()));
    return parseInt((_today - _birth) / 10000);
}
function affixZero(int) {
    if (int < 10) int = "0" + int;
    return "" + int;
}
var age = calculateAge(1980, 4, 22);
alert(age);
MikeoLeo
  • 1
  • 3
-2
$("#birthday").change(function (){


var val=this.value;

var current_year=new Date().getFullYear();
if(val!=null){
    var Split = val.split("-");
    var birth_year=parseInt(Split[2]);

    if(parseInt(current_year)-parseInt(birth_year)<parseInt(18)){

  $("#maritial_status").attr('disabled', 'disabled');
        var val2= document.getElementById("maritial_status");
        val2.value = "Not Married";
        $("#anniversary").attr('disabled', 'disabled');
        var val1= document.getElementById("anniversary");
        val1.value = "NA";

    }else{
        $("#maritial_status").attr('disabled', false);
        $("#anniversary").attr('disabled', false);

    }
}
});
mohd aarif
  • 11
  • 5
-2
function change(){
    setTimeout(function(){
        var dateObj  =      new Date();
                    var month    =      dateObj.getUTCMonth() + 1; //months from 1-12
                    var day      =      dateObj.getUTCDate();
                    var year     =      dateObj.getUTCFullYear();  
                    var newdate  =      year + "/" + month + "/" + day;
                    var entered_birthdate        =   document.getElementById('birth_dates').value;
                    var birthdate                =   new Date(entered_birthdate);
                    var birth_year               =   birthdate.getUTCFullYear();
                    var birth_month              =   birthdate.getUTCMonth() + 1;
                    var birth_date               =   birthdate.getUTCDate();
                    var age_year                =    (year-birth_year);
                    var age_month               =    (month-birth_month);
                    var age_date                =    ((day-birth_date) < 0)?(31+(day-birth_date)):(day-birth_date);
                    var test                    =    (birth_year>year)?true:((age_year===0)?((month<birth_month)?true:((month===birth_month)?(day < birth_date):false)):false) ;
                   if (test === true || (document.getElementById("birth_dates").value=== "")){
                        document.getElementById("ages").innerHTML = "";
                    }                    else{
                        var age                     =    (age_year > 1)?age_year:(   ((age_year=== 1 )&&(age_month >= 0))?age_year:((age_month < 0)?(age_month+12):((age_month > 1)?age_month:      (  ((age_month===1) && (day>birth_date) ) ? age_month:age_date)          )    )); 
                        var ages                    =    ((age===age_date)&&(age!==age_month)&&(age!==age_year))?(age_date+"days"):((((age===age_month+12)||(age===age_month)&&(age!==age_year))?(age+"months"):age_year+"years"));
                        document.getElementById("ages").innerHTML = ages;
                  }
                }, 30);

};
-2

This is my amended attempt (with a string passed in to function instead of a date object):

function calculateAge(dobString) {
    var dob = new Date(dobString);
    var currentDate = new Date();
    var currentYear = currentDate.getFullYear();
    var birthdayThisYear = new Date(currentYear, dob.getMonth(), dob.getDate());
    var age = currentYear - dob.getFullYear();

    if(birthdayThisYear > currentDate) {
        age--;
    }

    return age;
}

And usage:

console.log(calculateAge('1980-01-01'));
Mark P
  • 7
  • 1
  • You are passing a Date object in the function. His question is about converting a string like this: var dob='19800810'; – Erik Dekker Jan 03 '12 at 22:16
-3

Try this:

$('#Datepicker').change(function(){

var $bef = $('#Datepicker').val();
var $today = new Date();
var $before = new Date($bef);
var $befores = $before.getFullYear();
var $todays = $today.getFullYear();
var $bmonth = $before.getMonth();
var $tmonth = $today.getMonth();
var $bday = $before.getDate();
var $tday = $today.getDate();

if ($bmonth>$tmonth)
{$('#age').val($todays-$befores);}

if ($bmonth==$tmonth)
{   
if ($tday > $bday) {$('#age').val($todays-$befores-1);}
else if ($tday <= $bday) {$('#age').val($todays-$befores);}
}
else if ($bmonth<$tmonth)
{ $('#age').val($todays-$befores-1);} 
})