Javascript Date() 按天、月、年计算年龄工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12251325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:32:01  来源:igfitidea点击:

Javascript Date() to calculate age work by the day,months,years

javascriptjquery

提问by jennifer Jolie

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:

我想从用户日期生日开始显示几天、几个月和几年的持续时间。
这是我的代码,取自此处:Calculate age in JavaScript
How can 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.

用户生日是: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/

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

回答by ygssoni

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

演示在这里

回答by jennifer Jolie

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

对于那些不想被 format 限制的人mm/dd/yyyy,可以替换:

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.

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

回答by BrunoDee

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.

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

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.

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

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

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

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

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

回答by Faraz Shaikh

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

回答by Meera

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

回答by trincot

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.

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

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

这段代码定义了一个更通用的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);

回答by Bagz

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.

此函数将给出以年、月和日为单位的年龄。它的工作原理是先计算月份的差异,然后将该数字与出生日期相加,然后计算天数的差异。这样做的好处是让 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;