12

I want do show from user date birthday that a few days and months and years last.
Here is my code, as taken from here: Calculate age in JavaScript
How can it continue with the month and day, as:

user birthday is : 2010/04/29
The result should be like this: 2 years, 4 months, 5 days old.

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;
}

alert(getAge('2010/04/29'));

DEMO: http://jsfiddle.net/jFxb5/

Community
  • 1
  • 1
jennifer Jolie
  • 727
  • 6
  • 16
  • 30
  • 1
    helpful to u.. http://stackoverflow.com/questions/7833709/calculating-age-in-months-and-days – NIlesh Sharma Sep 03 '12 at 16:27
  • These answers are so complex! If you can include MomentJS, just use something along the lines of... var years = moment().diff('1935-12-31', 'years'); var days = moment().diff('1935-12-31', 'days'); – Ryan Loggerythm Dec 10 '20 at 20:17

11 Answers11

34
function getAge(dateString) {
  var now = new Date();
  var today = new Date(now.getYear(),now.getMonth(),now.getDate());

  var yearNow = now.getYear();
  var monthNow = now.getMonth();
  var dateNow = now.getDate();

  var dob = new Date(dateString.substring(6,10),
                     dateString.substring(0,2)-1,                   
                     dateString.substring(3,5)                  
                     );

  var yearDob = dob.getYear();
  var monthDob = dob.getMonth();
  var dateDob = dob.getDate();
  var age = {};
  var ageString = "";
  var yearString = "";
  var monthString = "";
  var dayString = "";


  yearAge = yearNow - yearDob;

  if (monthNow >= monthDob)
    var monthAge = monthNow - monthDob;
  else {
    yearAge--;
    var monthAge = 12 + monthNow -monthDob;
  }

  if (dateNow >= dateDob)
    var dateAge = dateNow - dateDob;
  else {
    monthAge--;
    var dateAge = 31 + dateNow - dateDob;

    if (monthAge < 0) {
      monthAge = 11;
      yearAge--;
    }
  }

  age = {
      years: yearAge,
      months: monthAge,
      days: dateAge
      };

  if ( age.years > 1 ) yearString = " years";
  else yearString = " year";
  if ( age.months> 1 ) monthString = " months";
  else monthString = " month";
  if ( age.days > 1 ) dayString = " days";
  else dayString = " day";


  if ( (age.years > 0) && (age.months > 0) && (age.days > 0) )
    ageString = age.years + yearString + ", " + age.months + monthString + ", and " + age.days + dayString + " old.";
  else if ( (age.years == 0) && (age.months == 0) && (age.days > 0) )
    ageString = "Only " + age.days + dayString + " old!";
  else if ( (age.years > 0) && (age.months == 0) && (age.days == 0) )
    ageString = age.years + yearString + " old. Happy Birthday!!";
  else if ( (age.years > 0) && (age.months > 0) && (age.days == 0) )
    ageString = age.years + yearString + " and " + age.months + monthString + " old.";
  else if ( (age.years == 0) && (age.months > 0) && (age.days > 0) )
    ageString = age.months + monthString + " and " + age.days + dayString + " old.";
  else if ( (age.years > 0) && (age.months == 0) && (age.days > 0) )
    ageString = age.years + yearString + " and " + age.days + dayString + " old.";
  else if ( (age.years == 0) && (age.months > 0) && (age.days == 0) )
    ageString = age.months + monthString + " old.";
  else ageString = "Oops! Could not calculate age!";

  return ageString;
}


alert(getAge('09/09/1989'));

DEMO HERE

ygssoni
  • 7,219
  • 2
  • 23
  • 24
  • 2
    this code isn't remotely correct - it'll return (for example) a negative number of months and/or days in many circumstances. – Alnitak Sep 03 '12 at 16:37
  • @kakarott:Thanks, but this don't work right, see for date `29/04/2010`: http://jsfiddle.net/x9paT/1/ – jennifer Jolie Sep 03 '12 at 17:18
  • 1
    Because its in MM/DD/YYYY format..try with 04/29/2010.. http://jsfiddle.net/x9paT/2/ – ygssoni Sep 03 '12 at 17:29
  • 1
    In this script aside from returning the "text" 20 years and 10 months and 20 days old, how do I only get the number months from the text?... – Tanker May 29 '14 at 00:35
  • I also need years and months from the method – Shamsul Arefin Aug 29 '18 at 06:11
  • 2
    If the date of birth is 28 February of the current year, and today's date is the next day (1 March), then this returns "Only 4 days old!". I must say the addition of "Only" makes this bug even more dramatic. ;-) – trincot Feb 05 '19 at 15:19
  • Tried input as 28 feb 2021, it says 13 days old it should be 10 days instead – Shardul Birje Mar 10 '21 at 18:28
  • That is the best solution. It worked for me. Thanks :)- – Sohail Shahzad Mar 14 '21 at 16:52
  • I have added an answer for this corner case of 28 February. Basically, Instead of using 31 everywhere, we can calculate the days of the months in the DOB. [link](https://stackoverflow.com/a/72009508/10433432) – sachinsaini Apr 26 '22 at 09:59
3

Try this:

function getAge(dateString) {
    var today = new Date();
    var DOB = new Date(dateString);
    var totalMonths = (today.getFullYear() - DOB.getFullYear()) * 12 + today.getMonth() - DOB.getMonth();
    totalMonths += today.getDay() < DOB.getDay() ? -1 : 0;
    var years = today.getFullYear() - DOB.getFullYear();
    if (DOB.getMonth() > today.getMonth())
        years = years - 1;
    else if (DOB.getMonth() === today.getMonth())
        if (DOB.getDate() > today.getDate())
            years = years - 1;

    var days;
    var months;

    if (DOB.getDate() > today.getDate()) {
        months = (totalMonths % 12);
        if (months == 0)
            months = 11;
        var x = today.getMonth();
        switch (x) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12: {
                var a = DOB.getDate() - today.getDate();
                days = 31 - a;
                break;
            }
            default: {
                var a = DOB.getDate() - today.getDate();
                days = 30 - a;
                break;
            }
        }

    }
    else {
        days = today.getDate() - DOB.getDate();
        if (DOB.getMonth() === today.getMonth())
            months = (totalMonths % 12);
        else
            months = (totalMonths % 12) + 1;
    }
    var age = years + ' years ' + months + ' months ' + days + ' days';
    return age;
}

console.log(getAge("2010/02/28"));
console.log(getAge("2010/03/01"));
trincot
  • 317,000
  • 35
  • 244
  • 286
Faraz Shaikh
  • 347
  • 1
  • 10
  • Please add some explanation as to why this answers the question. It uses `json.dob` which the OP does not have, and the output is not in the format that the OP is looking for. Would be good to use the same function signature as OP has. – trincot Jan 18 '19 at 22:37
  • @trincot 'json.dob' is given input (date of birth) and i tried this many times to calculate the years month and date as same format what mention is the question , it gives me output (26 years 8 months 20 days) 05/15/1992 on this input. – Faraz Shaikh Feb 04 '19 at 14:32
  • Please add this explanation inside your answer (edit it), and please take my comment into account: it is better to use the same variable names and function signature that the Asker has asked about, that way your answer looks really as an ... answer to *that* question. – trincot Feb 04 '19 at 15:16
  • Thank you for doing that. I turned your code into a runnable snippet (you can do this yourself in the future, using the button in the edit-toolbar) and added two outputs. Those show that there is a problem. By adding one day to 2010-02-28, the age *increments* (!) with almost one whole month. The value for number of days jumps also. The age should in fact just decrease with one day. In general, when increasing the birthday with one day, the age should decrease with one day. – trincot Feb 05 '19 at 12:48
1

For those who don't want to be restricted by format mm/dd/yyyy, you can replace:

var dob = new Date(dateString.substring(6,10),
                   dateString.substring(0,2)-1,                   
                   dateString.substring(3,5)                  
                  );

with:

var dob = new Date(dateString);

This allows me to use use 2012/09/30 and still get the right answer.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • This answer addresses a format choice that is not in the question. In fact it refers to code given in another answer and provides a way to make it work with the format used by the OP. Would better have been a comment to that other answer. – trincot Feb 08 '19 at 23:47
1

Calculates age in terms of years, months and days. Enter the dates in any valid date string format such as '1952/09/28', 'Sep 29, 1952', '09/28/1952' etc.

Takes 2 arguments - date of birth and the date on which to calculate age. You can leave the second argument out for today's date. Returns an object with years, months and days properties of age.

Uses the solar year value of 365.2425 days in a year.

@param birthDate Date of birth. @param ageAtDate The date on which to calculate the age. None for today's date. @returns {{years: number, months: number, days: number}}

function getAge(birthDate, ageAtDate) {
    var daysInMonth = 30.436875; // Days in a month on average.
    var dob = new Date(birthDate);
    var aad;
    if (!ageAtDate) aad = new Date();
    else aad = new Date(ageAtDate);
    var yearAad = aad.getFullYear();
    var yearDob = dob.getFullYear();
    var years = yearAad - yearDob; // Get age in years.
    dob.setFullYear(yearAad); // Set birthday for this year.
    var aadMillis = aad.getTime();
    var dobMillis = dob.getTime();
    if (aadMillis < dobMillis) {
        --years;
        dob.setFullYear(yearAad - 1); // Set to previous year's birthday
        dobMillis = dob.getTime();
    }
    var days = (aadMillis - dobMillis) / 86400000;  
    var monthsDec = days / daysInMonth; // Months with remainder.
    var months = Math.floor(monthsDec); // Remove fraction from month.
    days = Math.floor(daysInMonth * (monthsDec - months));
    return {years: years, months: months, days: days};
}
BrunoDee
  • 21
  • 4
  • This returns 1 year exactly for `getAge("2016-02-29", "2017-03-01")`. Add one day to the first date and the result is still the same. Apparently the leap day does not count. – trincot Feb 05 '19 at 15:55
1

As I saw an issue with the accepted solution (see my comment there), I present here my own version, which guarantees there will be no "jumps" in the number of days when increasing the date of birth by only 1.

This code defines a more generic DateInterval class for representing the difference between two dates. The function getAge then becomes a thin implementation based on that class.

class DateInterval {
    constructor(start, end) { // two Date instances
        if (start > end) [start, end] = [end, start]; // swap
        this.days = end.getDate() - start.getDate();
        this.months = end.getMonth() - start.getMonth();
        this.years = end.getFullYear() - start.getFullYear();
        if (this.days < 0) {
            // Add the number of days that are left in the month of the start date
            this.days += (new Date(start.getFullYear(), start.getMonth() + 1, 0)).getDate();
            this.months--;
        }
        if (this.months < 0) {
            this.months += 12;
            this.years--;
        }
    }
    toString() {
        const arr = ["years", "months", "days"].map(p => 
            this[p] && (this[p] + " " + p.slice(0, this[p] > 1 ? undefined : -1))
        ).filter(Boolean);
        if (!arr.length) return "0 days";    
        const last = arr.pop();
        return arr.length ? [arr.join(", "), last].join(" and ") : last;
    }
}

function getAge(dateString) {
    let today = new Date();
    today.setHours(0,0,0,0);
    let dob = new Date(dateString);
    dob.setHours(0,0,0,0);
    return new DateInterval(dob, today) + " old.";
}

// Demo: increment the date of birth by 1 at each test:
let d = new Date(2000, 1, 1);
setInterval(() => {
    const s = d.toJSON().slice(0,10);
    console.log("Someone born on " + s + " is now " + getAge(s));
    d = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1);
}, 300);
trincot
  • 317,000
  • 35
  • 244
  • 286
1

This function will give the age in years, months and days. It works by calculating the difference in months first, then adding that number to the date of birth, and then calculating the difference in days. The beauty of this is that it is left to the Date object to worry about leap years and difference in days in each month.

    var nowDate = new Date(new Date().setHours(0, 0, 0, 0));
    // Example date of birth.
    var dobDate = new Date["03/31/2001"];

    var years = nowDate.getFullYear() - dobDate.getFullYear();
    var months = nowDate.getMonth() - dobDate.getMonth();
    var days = nowDate.getDate() - dobDate.getDate();

    // Work out the difference in months.
    months += years * 12;
    if (days < 0) {
      months -= 1;
    }
    // Now add those months to the date of birth.
    dobDate.setMonth(dobDate.getMonth() + months);
    // Calculate the difference in milliseconds.
    var diff = nowDate - dobDate;
    // Divide that by 86400 to get the number of days.
    var days = Math.round(diff / 86400 / 1000);
    // Now convert months back to years and months.
    years = parseInt(months / 12);
    months -= (years * 12);
    // Format age as "xx years, yy months, zz days"
    var text = "";
    if (years) {
      text = years + (years > 1 ? " years" : " year");
    }
    if (months) {
      if (text.length) {
        text = text + ", ";
      }
      text = text + months + (months > 1 ? " months" : " month")
    }
    if (days) {
      if (text.length) {
        text = text + ", ";
      }
      text = text + days + (days > 1 ? " days" : " day")
    }
    if (nowDate == dobDate) {
      text = "Newborn"
    }
    return text;
Bagz
  • 11
  • 2
0
 function CalculateAge(DobString) {


        $("#age").val(getAge(DobString));
    }

     function getAge(dateString) {
            var now = new Date('2019/01/20');
            var today = new Date(now.getYear(), now.getMonth(), now.getDate());

            var yearNow = now.getYear();
            var monthNow = now.getMonth();
            var dateNow = now.getDate();

            var dob = new Date(dateString.substring(6, 10),
                               dateString.substring(3, 5) - 1,
                               dateString.substring(0, 2) 
                               );

            var yearDob = dob.getYear();
            var monthDob = dob.getMonth();
            var dateDob = dob.getDate();
            var age = {};
            var ageString = "";
            var yearString = "";
            var monthString = "";
            var dayString = "";


            yearAge = yearNow - yearDob;

            if (monthNow >= monthDob)
                var monthAge = monthNow - monthDob;
            else {
                yearAge--;
                var monthAge = 12 + monthNow - monthDob;
            }

            if (dateNow >= dateDob)
                var dateAge = dateNow - dateDob;
            else {
                monthAge--;
                var dateAge = 31 + dateNow - dateDob;

                if (monthAge < 0) {
                    monthAge = 11;
                    yearAge--;
                }
            }

            age = {
                years: yearAge,
                months: monthAge,
                days: dateAge
            };

            if (age.years > 1) yearString = " years";
            else yearString = " year";
            if (age.months > 1) monthString = " months";
            else monthString = " month";
            if (age.days > 1) dayString = " days";
            else dayString = " day";


            if ((age.years > 0) && (age.months > 0) && (age.days > 0))
                ageString = age.years + yearString + ", " + age.months + monthString + " " + age.days + dayString + " ";
            else if ((age.years == 0) && (age.months == 0) && (age.days > 0))
                ageString = " " + age.days + dayString + " ";
            else if ((age.years > 0) && (age.months == 0) && (age.days == 0))
                ageString = age.years + yearString + " ";
            else if ((age.years > 0) && (age.months > 0) && (age.days == 0))
                ageString = age.years + yearString + "  " + age.months + monthString + " ";
            else if ((age.years == 0) && (age.months > 0) && (age.days > 0))
                ageString = age.months + monthString + " " + age.days + dayString + " ";
            else if ((age.years > 0) && (age.months == 0) && (age.days > 0))
                ageString = age.years + yearString + " " + age.days + dayString + " ";
            else if ((age.years == 0) && (age.months > 0) && (age.days == 0))
                ageString = age.months + monthString + " ";
            else ageString = "Oops! Could not calculate age!";

            return ageString;
        }
Til
  • 5,150
  • 13
  • 26
  • 34
Meera
  • 1
  • 3
  • Without any explanation of how this answers the question, this is not of great use. A mere code dump is not very enlightening. – trincot Feb 05 '19 at 16:00
0

Answered by @ygssoni is partially correct. Rest you can do:

Instead of using 31 while calculating days:

 if (dateNow >= dateDob)
    var dateAge = dateNow - dateDob;
  else {
    monthAge--;
    var dateAge = 31 + dateNow - dateDob;

    if (monthAge < 0) {
      monthAge = 11;
      yearAge--;
    }
  }

I have corrected this: Write this function and use it inside getAge() function.

function daysInMonth (month, year) {
    return new Date(year, month, 0).getDate();
}
if (dateNow >= dateDob)
    var dateAge = dateNow - dateDob;
  else {
    monthAge--;
    noOfDaysInDOB = daysInMonth(monthDob,yearDob);
    var dateAge = noOfDaysInDOB + dateNow - dateDob;

    if (monthAge < 0) {
      monthAge = 11;
      yearAge--;
    }
  }

Created video tutorial in Hindi for the same: https://youtu.be/TnOwcvppV6U

sachinsaini
  • 53
  • 1
  • 10
0

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
0

this code return array [minutes_ago,hours_ago,days_ago,month_ago,years_ago]

function get_minutes_ago(time_minutes){
    if (time_minutes < 60)
    {
        return [time_minutes,0];
    }else{
        return [0,0];
    }
}

function get_hours_ago(time_minutes){
    if (time_minutes < (24 * 60) )
    {
        return [time_minutes / (60), (time_minutes % 60)];
    }else{
        return [0,0];
    }
}

function get_days_ago(time_minutes){
    if (time_minutes < (30 * 24 * 60) )
    {
        return [time_minutes / (24*60),(time_minutes % (24*60))];
    }else{
        return [0,0];
    }
}

function get_month_ago(time_minutes){
    if ( time_minutes < (12 * 30 * 24 * 60) )
    {
        return [time_minutes / (30*24*60),time_minutes % (30*24*60)];
    }else{
        return [0,0];
    }
}

function get_years_ago(time_minutes){
    if (time_minutes >= (12 * 30 * 24 * 60) )
    {
        return [time_minutes / (12*30*24*60),time_minutes % (12*30*24*60)];
    }else{
        return [0,0];
    }
}

function getAge(dateString) {
    tmp = new Date(dateString);
    now = new Date();
    var diff = now.getTime() - tmp.getTime();
    var total_minutes = Math.floor(diff/60/1000)
    var minutes_ago = 0;
    var hours_ago = 0;
    var days_ago = 0;
    var month_ago = 0;
    var years_ago = 0;
    if ( total_minutes >= (12*30*24*60) ){

        years_ago = get_years_ago(total_minutes)[0];
        month_ago = get_month_ago(get_years_ago(total_minutes)[1])[0];
        days_ago = get_days_ago(get_month_ago(get_years_ago(total_minutes)[1])[1])[0];
        hours_ago = get_hours_ago(get_days_ago(get_month_ago(get_years_ago(total_minutes)[1])[1])[1])[0];
        minutes_ago = get_minutes_ago(get_hours_ago(get_days_ago(get_month_ago(get_years_ago(total_minutes)[1])[1])[1])[1])[0];
    }

    if( total_minutes < (12*30*24*60) && total_minutes >= (30*24*60))
    {
        month_ago = get_month_ago(total_minutes)[0];
        days_ago = get_days_ago(get_month_ago(total_minutes)[1])[0];
        hours_ago = get_hours_ago(get_days_ago(get_month_ago(total_minutes)[1])[1])[0];
        minutes_ago = get_minutes_ago(get_hours_ago(get_days_ago(get_month_ago(total_minutes)[1])[1])[1])[0];
    }

    if (total_minutes < (30*24*60) && total_minutes >= (24*60)){
        days_ago = get_days_ago(total_minutes)[0];
        hours_ago = get_hours_ago(get_days_ago(total_minutes)[1])[0];
        minutes_ago = get_minutes_ago(get_hours_ago(get_days_ago(total_minutes)[1])[1])[0];
    }

    if( total_minutes < (24*60) && total_minutes >= 60){
        hours_ago = get_hours_ago(total_minutes)[0];
        minutes_ago = get_minutes_ago(get_hours_ago(total_minutes)[1])[0];
    }

    if(total_minutes < 60){
        minutes_ago = get_minutes_ago(total_minutes)[0];
    }

    return [Math.floor(minutes_ago),Math.floor(hours_ago),Math.floor(days_ago),Math.floor(month_ago),Math.floor(years_ago)];
}

usage

getAge( Date.now() - ( 24 * 60 * 60 * 1000 ) ); // for return [0, 0, 1, 0, 0]

getAge(Date.now() - ( 30 * 24 * 60 * 60 * 1000 )) // for return [0, 0, 0, 1, 0]

or

var ss = new Date("2010/2/2");
getAge(ss.getTime()) // return [30, 9, 14, 6, 12]
0
// Make a button that display the current date and time in local format on the page. 


function mydateis(){
    const d = new Date();
let text = d.toLocaleString();
document.getElementById("date").innerHTML = text;



var year_born = prompt("Please enter your date of birth:", 1998);
var month_born = prompt("Please enter your month:", 1);
var month_day = prompt("Please enter your day:", 1);
 

function getAge(birthYear,month_born,month_day){
    var currentDate = new Date();
    var currentYear = currentDate.getFullYear();
    var currentmonth = currentDate.getMonth();
    var currentday = currentDate.getDate();
    console.log(currentDate);
    console.log(currentDate.getDate());
    age = currentYear - birthYear;
    month = currentmonth - month_born;
    day = currentday - month_day;
    return age,month,day;
}

calculatedAge = getAge(year_born,month_born,month_day);
 document.getElementById("yearsold").innerHTML ="you have yeyre is" + age+ "  and  "+month+"  month and  days is  "+day ;


}

enter image description here