Calculate age given the birth date in the format YYYYMMDD
Asked Answered
W

49

401

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);
Weanling answered 30/10, 2010 at 18:7 Comment(8)
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.Atticism
I did but it fails to work on IE9 Beta so I had to do it by hand.Weanling
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.Crusado
Thank you Brock. I was hoping there was a more elegant way of doing this than that which seems a bit crude.Weanling
@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.Crusado
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.Weanling
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 0Hydrolyze
See latest post using Temporal API.Swineherd
S
322

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.


Skyros answered 24/2, 2014 at 9:51 Comment(40)
This returns 0 years for dates like 2000-02-29 to 2001-02-28 when it probably should return 1.Marilynnmarimba
I commented on Naveen's answer too. It does the same thing, as does every other answer I tried—except mine of course. :-)Marilynnmarimba
@Marilynnmarimba 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.Desdamona
There's something else going on too, it thinks 2012-02-28 to 2013-02-27 is one year.Marilynnmarimba
@RobG, what part of "not precise", is it that you are having a hard time to comprehend?Desdamona
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.Marilynnmarimba
@Marilynnmarimba 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.Desdamona
@vee It needs a Date as input.Desdamona
@vee Create a question for it on the site.Desdamona
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.Incurable
@KristofferDorph Thanks, I appreciate that :) Although naveens answer is faster, and more precise. Mine is more of a readable hack.Desdamona
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.Jaymie
@Jaymie 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)) ?Desdamona
@AndréSnedeHansen possibly not. Thank you, I shall check!Jaymie
@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() - 1970Giddy
This doesn't give a age in years as intended based on the snippet of OPBodwell
@BruceLim Nice explanation, I really have something to go on here.Desdamona
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.Roundfaced
@BruceLim Jep, I am aware of that issue, as I state in my answer, naveens post is the better solution to this.Desdamona
@BruceLim why the answer is wrong? what is your explanation about that ?Farahfarand
The link is dead nowDeodorize
The jsperf link works fine for me today. I would like to see naveen's answer added to the comparisons.Chafe
@CodeswithHammer Naveens answer, is the first test.Desdamona
@AndréSnedeKock: Oh, so it is. Thanks. (I thought I had compared the two and found them different.)Chafe
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.Tabina
@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.Desdamona
@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.Tabina
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();Tabina
@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.Desdamona
Thank you for editing the question to mention that. I think it will help others.Tabina
@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.Desdamona
@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 wellStandridge
@Standridge 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.Desdamona
Here's a one line version of this incase anyone wants it: new Date(new Date() - new Date(birthday)).getFullYear() - 1970Trochilus
@Trochilus 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.Desdamona
why 1970 is used? @AndréSnedeKockPraedial
@ChristineShaji it is the epoch used in Javascript.Desdamona
Oh alright.. Thanks for the information. @AndréSnedeKockPraedial
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.Flea
This doesn't work when the given birthday is today, it's not adding a year to the age....Ganda
E
681

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/

Entablature answered 17/8, 2011 at 11:18 Comment(9)
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: jsbin.com/ehaqiw/1/editGlasswort
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).Marilynnmarimba
@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) en.wikipedia.org/wiki/February_29 For all the above this algo is correct IF March 1th is the leapyear result one needsFoal
@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.Marilynnmarimba
@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.Foal
@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.Marilynnmarimba
@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 ?!?Foal
Ha, yes, 31 January plus one month. :-)Marilynnmarimba
@Dr.G: For me, its 63. jsfiddle.net/codeandcloud/o86au3dn Please double-check your codeEntablature
S
322

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.


Skyros answered 24/2, 2014 at 9:51 Comment(40)
This returns 0 years for dates like 2000-02-29 to 2001-02-28 when it probably should return 1.Marilynnmarimba
I commented on Naveen's answer too. It does the same thing, as does every other answer I tried—except mine of course. :-)Marilynnmarimba
@Marilynnmarimba 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.Desdamona
There's something else going on too, it thinks 2012-02-28 to 2013-02-27 is one year.Marilynnmarimba
@RobG, what part of "not precise", is it that you are having a hard time to comprehend?Desdamona
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.Marilynnmarimba
@Marilynnmarimba 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.Desdamona
@vee It needs a Date as input.Desdamona
@vee Create a question for it on the site.Desdamona
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.Incurable
@KristofferDorph Thanks, I appreciate that :) Although naveens answer is faster, and more precise. Mine is more of a readable hack.Desdamona
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.Jaymie
@Jaymie 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)) ?Desdamona
@AndréSnedeHansen possibly not. Thank you, I shall check!Jaymie
@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() - 1970Giddy
This doesn't give a age in years as intended based on the snippet of OPBodwell
@BruceLim Nice explanation, I really have something to go on here.Desdamona
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.Roundfaced
@BruceLim Jep, I am aware of that issue, as I state in my answer, naveens post is the better solution to this.Desdamona
@BruceLim why the answer is wrong? what is your explanation about that ?Farahfarand
The link is dead nowDeodorize
The jsperf link works fine for me today. I would like to see naveen's answer added to the comparisons.Chafe
@CodeswithHammer Naveens answer, is the first test.Desdamona
@AndréSnedeKock: Oh, so it is. Thanks. (I thought I had compared the two and found them different.)Chafe
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.Tabina
@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.Desdamona
@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.Tabina
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();Tabina
@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.Desdamona
Thank you for editing the question to mention that. I think it will help others.Tabina
@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.Desdamona
@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 wellStandridge
@Standridge 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.Desdamona
Here's a one line version of this incase anyone wants it: new Date(new Date() - new Date(birthday)).getFullYear() - 1970Trochilus
@Trochilus 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.Desdamona
why 1970 is used? @AndréSnedeKockPraedial
@ChristineShaji it is the epoch used in Javascript.Desdamona
Oh alright.. Thanks for the information. @AndréSnedeKockPraedial
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.Flea
This doesn't work when the given birthday is today, it's not adding a year to the age....Ganda
P
87

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.

Poult answered 13/6, 2018 at 0:59 Comment(4)
Pretty damn neat - could you elaborate what the 3.15576e+10 means?Mocha
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)Poult
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.Physicochemical
const NUMBER_OF_MILI_SECONDS_IN_YEAR = 31536000000; return Math.floor( (CurrentDate - BirthDay.getTime()) / NUMBER_OF_MILI_SECONDS_IN_YEAR );Plainlaid
I
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! :-)

Incurable answered 21/3, 2013 at 19:0 Comment(10)
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.Weanling
That is true, just added a comment about that :-)Incurable
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.Antispasmodic
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).Incurable
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?Shorter
@FrankJensen Hi Frank, i was curious too and found this answer: double tilde converts float to integer GreetingsGlucoprotein
@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' === 21Incurable
~~((Date.now() - birthday) / (31557600000)) is not supported in IE8.0 Object doesn't support this property or methodForejudge
this is really age, not named age, when we deal with health management, we use this is more righter than the named age.Unexperienced
@Weanling 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.Beadledom
T
70

With momentjs:

/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')
Titleholder answered 6/5, 2014 at 4:29 Comment(6)
@RicardoPontual this requires momentjs, so can't be the best answer.Embattle
@Embattle indeed, for an answer to be the best one, it should at least require jQuery ;)Marquess
@Marquess It totally depends on the development environment!Embattle
@Embattle relax, it's a joke ;) see: meta.stackexchange.com/a/19492/173875Marquess
@Marquess I knew that it is a joke ;)Embattle
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'Nature
S
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
Speiss answered 30/10, 2010 at 19:0 Comment(5)
Ah yes, I missed the leap year. Thank you.Weanling
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.Crusado
@BrockAdams Why is this? I am having this problem at the moment. Thanks.Fear
@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.Crusado
CMS Hi :-) I wrote this question (#16436481) 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 ?Choric
S
14

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
}
Shelby answered 12/12, 2012 at 6:43 Comment(0)
L
12

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;
}
Lenhart answered 12/2, 2013 at 18:8 Comment(1)
this is the really best answer, it is not top answer, just because the var name is too long:)Unexperienced
E
8

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('');
Epicanthus answered 22/6, 2021 at 16:43 Comment(0)
S
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';
}
Signboard answered 31/10, 2010 at 8:20 Comment(1)
Thanks easy to find age in years months and daysOctennial
E
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
Electroanalysis answered 24/11, 2016 at 11:12 Comment(1)
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...Penn
R
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"));
Rhys answered 12/3, 2019 at 21:10 Comment(1)
This is the version that made the most sense to me.Urushiol
A
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));
Atticism answered 30/10, 2010 at 19:19 Comment(5)
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.Crusado
@Brock: Thanks. If I'm not mistaken, I've corrected this erroneous behaviour.Atticism
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.Crusado
@Brock: I fully agree: I have to think about what this function does and that's never a good thing.Atticism
Shouldn't "if (doyNow < doyBirth)" be "if (doyNow <= doyBirth)" ? In all my tests, the day has been off by one and that fixed it.Simpson
A
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.

Antedate answered 16/6, 2012 at 16:53 Comment(1)
n is undefined. I think you mean now.getFullYear()Newton
M
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')
Monitory answered 15/3, 2013 at 10:54 Comment(1)
Thanks for your suggestion at https://mcmap.net/q/87695/-fancybox-not-displaying-youtube-video-since-ios6 good catch.Sediment
A
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);
Arman answered 17/2, 2013 at 19:19 Comment(1)
Should 2000-02-29 to 2001-02-28 be one year? If so, then the above isn't perfect. :-)Marilynnmarimba
N
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);
}
Ningpo answered 8/1, 2017 at 18:40 Comment(0)
H
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
Hutchinson answered 18/5, 2017 at 10:4 Comment(0)
R
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>
Rundlet answered 4/4, 2019 at 11:31 Comment(2)
I like it a lot, upvoted. It's different and it works great.Discomfit
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=1Blight
G
1

Works perfect for me, guys.

getAge(birthday) {
    const millis = Date.now() - Date.parse(birthday);
    return new Date(millis).getFullYear() - 1970;
}
Ganiats answered 8/8, 2018 at 13:38 Comment(2)
I tried this today the 16th of Feb 2020 with tomorrow's date last year console.log(getAge("2020-02-17")) and it returns 1Blight
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.Popish
A
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()));
Acromegaly answered 7/12, 2021 at 0:48 Comment(3)
The code doesn't work with format YYYYMMDD, which is the question's requirement.Olivette
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewOlivette
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.Acromegaly
P
1
/*
    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;           
}
Peterus answered 26/5, 2023 at 22:32 Comment(0)
B
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.

Brei answered 18/12, 2012 at 16:30 Comment(0)
P
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;
            }
        }
    }
Pleasing answered 11/1, 2015 at 19:50 Comment(1)
strings or date objects for input as per OPBodwell
B
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>
Bodwell answered 9/2, 2016 at 5:44 Comment(0)
M
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);
    }
}
Menell answered 7/4, 2016 at 4:40 Comment(0)
G
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

Grivet answered 8/4, 2016 at 13:52 Comment(0)
E
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;
    }
 }
Epigrammatize answered 4/5, 2016 at 15:15 Comment(0)
W
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--;
Woodley answered 15/2, 2018 at 9:8 Comment(1)
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)Penn
B
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);
    }
}
Becerra answered 20/8, 2018 at 18:11 Comment(0)
E
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;
  };
Edgeways answered 2/1, 2019 at 13:28 Comment(0)
G
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();
}
Gurrola answered 8/10, 2020 at 18:50 Comment(0)
Y
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
        })()
Yarborough answered 1/4, 2023 at 9:5 Comment(0)
I
0

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

differenceInYears( new Date(),parse('19800810','yyyyMMdd', new Date()) 
Incompetence answered 7/7, 2023 at 12:25 Comment(0)
S
0

Update 25 Nov 2023

Just in case you land here from googling the net.

The age can be calculated in Javascript more accurately using the Temporal API.

The following example uses the until method to calculate the Temporal.Duration object which is the elapsed duration from the Date of Birth DoB until today's date.

Because the Temporal.Duration.toLocaleString() does not work yet because the Intl.DurationFormat is not yet implemented, a custom helper function is used for formatting the age duration using Intl.NumberFormat() and the Intl.ListFormat()

The output will be shown as years, months, and days

The function can take a locale to display the output in a different language. The default is en-US.

<script type='module'>
import * as TemporalModule from 'https://cdn.jsdelivr.net/npm/@js-temporal/[email protected]/dist/index.umd.js'
const Temporal = temporal.Temporal;


function age(DoB,{locale="en-US"}={}) {
let duration= Temporal.PlainDate.from(DoB).until(Temporal.Now.plainDateISO(),
{smallestUnit: "day", largestUnit:"year", relativeTo: DoB});
return format(duration);

// custom formatting function follows, as 'Temporal.Duration.toLocaleString()' does not work
// because 'Intl.DurationFormat' is not yet implemented.

function format(duration){
return new Intl.ListFormat(locale,{style:'long',type:'conjunction'}).format(
["year","month","day"].map(unit=>[unit,duration[unit+"s"]]).map(([unit,v])=>v?new Intl.NumberFormat(locale,{style: "unit",unit,unitDisplay:'long'}).format(v):0).filter(v=>v));
}
}
//-------------Test Examples -----------------
console.log(age("2000-01-01"));
console.log(age("1975-03-15"));
console.log(age("1975-03-15",{locale:"fr-FR"}));
console.log(age("1975-03-15",{locale:"ar-QA"}));

</script>
Swineherd answered 25/11, 2023 at 20:53 Comment(0)
C
-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!

Contented answered 7/11, 2013 at 3:3 Comment(2)
Like all the others, it thinks 2000-02-29 to 2001-02-28 is zero years.Marilynnmarimba
I've updated my answer to accommodate the leap year edge case. Thanks @MarilynnmarimbaContented
A
-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;
}
Agronomics answered 26/3, 2014 at 8:12 Comment(0)
D
-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]
Directions answered 25/6, 2015 at 8:10 Comment(0)
P
-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;
Pyotr answered 16/8, 2015 at 12:29 Comment(0)
C
-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;
    }
Certified answered 10/11, 2015 at 5:40 Comment(0)
A
-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)
}
Alfy answered 3/10, 2020 at 6:59 Comment(0)
W
-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);
Wylen answered 30/5, 2022 at 23:55 Comment(0)
I
-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'));
Impersonate answered 3/1, 2012 at 22:9 Comment(1)
You are passing a Date object in the function. His question is about converting a string like this: var dob='19800810';Measurable
M
-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;
}
Marilynnmarimba answered 21/3, 2014 at 15:9 Comment(4)
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.Desdamona
"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.Marilynnmarimba
It's definetely not an "administrative thing", its purely defined in time specifications, which I am not going to dig through.Desdamona
@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.Marilynnmarimba
B
-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", "");

}

Badmouth answered 16/6, 2014 at 17:5 Comment(0)
S
-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);
Sextuple answered 21/4, 2015 at 7:21 Comment(0)
L
-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);

    }
}
});
Lawler answered 15/9, 2015 at 5:3 Comment(0)
B
-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);

};
Bushwa answered 16/9, 2015 at 10:35 Comment(1)
Please add descriptionAbilene
P
-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);} 
})
Peptonize answered 31/8, 2014 at 10:5 Comment(1)
question is for vanilla jsPoult

© 2022 - 2024 — McMap. All rights reserved.