11

我想从用户日期生日开始显示几天、几个月和几年。
这是我的代码,取自此处:Calculate age in JavaScript
How can it continue with the month and day, as:

用户生日是:2010/04/29
结果应该是这样的:2 岁 4 个月 5 天。

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

演示:http: //jsfiddle.net/jFxb5/

4

7 回答 7

31
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'));

在这里演示

于 2012-09-03T16:34:50.437 回答
1

不想被格式限制的mm/dd/yyyy可以替换:

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

和:

var dob = new Date(dateString);

这使我可以使用 2012/09/30 并且仍然得到正确的答案。

于 2013-01-01T19:29:28.460 回答
1

以年、月和日为单位计算年龄。以任何有效的日期字符串格式输入日期,例如“1952/09/28”、“Sep 29, 1952”、“09/28/1952”等。

接受 2 个参数 - 出生日期和计算年龄的日期。您可以将第二个参数留到今天的日期。返回具有年、月和日属性的对象年龄。

使用一年中 365.2425 天的太阳年值。

@parambirthDate 出生日期。@param ageAtDate 计算年龄的日期。今天的日期没有。@returns {{年:数字,月:数字,天:数字}}

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};
}
于 2016-05-15T00:19:27.277 回答
1

试试这个:

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

于 2019-01-18T22:02:37.853 回答
1

当我看到已接受的解决方案存在问题时(请参阅我的评论),我在这里展示了我自己的版本,它保证在仅将出生日期增加 1 时天数不会“跳跃”。

此代码定义了一个更通用的DateInterval类来表示两个日期之间的差异。然后该函数getAge成为基于该类的瘦实现。

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

于 2019-02-05T15:44:21.420 回答
1

此函数将以年、月和日为单位给出年龄。它的工作原理是首先计算月份的差异,然后将该数字添加到出生日期,然后计算天数的差异。这样做的美妙之处在于,让 Date 对象来担心闰年和每个月的天数差异。

    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;
于 2019-10-23T00:42:06.237 回答
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;
        }
于 2019-01-24T05:14:08.360 回答