Javascript Date()按日,月,年计算年龄工作

时间:2012-09-03 16:23:07

标签: javascript jquery

我希望从用户日期生日那里显示几天,几个月和几年的时间 这是我的代码,从这里开始:Calculate age in JavaScript
如何继续这个月和日,如:

  

用户生日是: 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'));

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

7 个答案:

答案 0 :(得分:19)

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

答案 1 :(得分: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并仍然得到正确的答案。

答案 2 :(得分:1)

以年,月和日计算年龄。输入日期 在任何有效的日期字符串格式中,例如&#39; 1952/09 / 28&#39;,&#39; 1952年9月29日&#39;, &#39 09 /一千九百五十二分之二十八&#39;等

取2个论点 - 出生日期和计算日期 年龄。您可以在今天的日期留下第二个参数。 返回具有年,月和日属性的对象。

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

@param birthDate出生日期。 @param ageAtDate计算年龄的日期。没有 今天的约会。 @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};
}

答案 3 :(得分: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"));

答案 4 :(得分: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;
        }

答案 5 :(得分:0)

当我看到可接受的解决方案存在问题时(请参阅我的评论),在这里我提出自己的版本,该版本可以保证将出生日期仅增加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);

答案 6 :(得分:0)

此功能将以年,月和日为单位给出年龄。它的工作原理是首先计算月份差异,然后将该数字添加到出生日期,然后计算天差异。这样做的好处是让Date对象担心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;