생년월일을 YYYYMMDD 형식으로 계산하십시오.


285

YYYYMMDD 형식의 생년월일을 기준으로 나이를 몇 년으로 어떻게 계산할 수 있습니까? 사용할 수 있습니까?Date() 기능을?

현재 사용중인 솔루션보다 더 나은 솔루션을 찾고 있습니다.

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


포맷팅을 염두에 두십시오. 코드 (010101) 버튼 또는 Ctrl-K를 사용하여 4 개의 공백으로 코드를 들여 쓰기 만하면됩니다.
— Marcel Korpel

나는했지만 IE9 Beta에서 작동하지 않아서 직접해야했습니다.
— Francisc

4
나이를 계산할 때 기존 솔루션보다 현재 솔루션이 더 좋습니다. 줄리오 산토스의 대답은 본질적으로 같은 것입니다. 다른 답변은 여러 조건에서 부정확 한 결과를 제공하며 덜 간단하거나 덜 효율적일 수 있습니다.
— Brock Adams

고마워요. 나는 조금 조잡한 것처럼 보이는 것보다 더 우아한 방법이 있기를 바랐습니다.
— Francisc

4
@Francisc, 그것은 조잡하지만, Date그것이 캡슐화되면 객체가해야 할 일입니다. 사람들은 JS가 Date다루는 짜증나는 것에 관한 책을 쓸 수있었습니다 . ... 가끔 하루를 쉬면서 살 수 있다면 근사치 : AgeInYears = Math.floor ( (now_Date - DOB_Date) / 31556952000 )는 가능한 한 간단합니다.
— Brock Adams

답변:


245

가독성을 원할 것입니다.

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

부인 성명: 이것은 또한 정밀한 문제가 있으므로 완전히 신뢰할 수는 없습니다. 시간대에 따라 몇 시간, 몇 년 또는 일광 절약 시간 제로 해제 될 수 있습니다.

대신 정밀도가 매우 중요한 경우 라이브러리를 사용하는 것이 좋습니다. 또한 @Naveens post시간에 의존하지 않기 때문에 아마도 가장 정확할 것입니다.


벤치 마크 : http://jsperf.com/birthday-calculation/15


3
2000년 2월 29일 2001년 2월 28일에 같은 날짜이 0을 반환 년 아마 1. 반환해야 할 때
— RobG

16
@RobG 저는 기술적으로 2000 년 2 월 29 일에서 2001 년 2 월 28 일까지 1 년이 지났다고 생각하지 않습니다. 2000-02-28에서 2001-02-28은 1 년이므로 2000-02-29에서 2001-02-28은 1 년 미만이어야합니다.
— André Snede Kock

3
"정확하지 않음"의 의미에 대해 자세히 설명하지 않았지만 추가 정보가 도움이 될 것으로 생각했습니다. 문제를 해결하거나 답변을 삭제하는 것을 고려할 수 있습니다.
— RobG

1
@RobG 실제로 했어요. 나는 또한 내 것보다 더 나은 해결책을 지적했다. 내 솔루션은 약간의 정밀한 문제가 있지만 목적의 범위 내에서 읽기 쉬운 방식으로 문제를 해결합니다.
— André Snede Kock

1
가독성과 속도에 대한 내 대답 ;-) +1에 나와있는 미친 나눗셈이 없기 때문에 @ AndréSnedeHansen과 대답도 빠릅니다.
— Kristoffer Dorph

506

이 시도.

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

나는 당신의 코드에서 조잡하게 보이는 것이 부분이라고 믿습니다 substr.

피들 : http://jsfiddle.net/codeandcloud/n33RJ/


사용 예를들 수 있습니까? getAge (y, m, d)와 같이 3 개의 개별 인수를 사용하도록 함수를 수정하지 않고 작동하지 못했습니다. 예를 들면 : jsbin.com/ehaqiw/1/edit
— 동부 서머 타임

다른 많은 사람들과 마찬가지로, 2000-02-29에서 2001-02-28까지는 0 년이라고 생각합니다. 2001 년 1 월 1 일은 1 년 1 일이므로 1 일 가능성이 높습니다.
— RobG

3
@RobG : '축하합니다'(그 질문에 대한 일반적인 대답은 실제로 '실제 날짜에 가장 가까운 주말'인 것 같습니다)와 같은 생년월일 은 다음과 같은 상황에 따라 다릅니다 . ), 법률 (저것을 과소 평가하지 마십시오), 종교 및 개인 취향 (단체 행동 포함) : 어떤 이유 : "2 월에 태어났습니다", 다른 이유 : "2 월 28 일 이후에 태어났습니다" (가장 일반적으로 3 월 1 일) en.wikipedia.org/wiki/February_29 위의 모든 사항에 대해이 알고리즘은 3 월 1 일이 필요한 윤년 결과 인 경우 정확합니다
— GitaarLAB

3
@RobG : 'plus x month (s)'의 욕구는 몇 년 동안 인간의 연령 개념과 관련이 없습니다. 일반적인 인간 개념은 달력이 같은 달 번호와 일 번호 (시작 날짜와 비교)가 같을 때 나이 (InYears) 카운터가 매일 (시간을 무시하고) 증가한다는 것입니다 : 2000-02-28 ~ 2001-02 -27 = 0 세 및 2000-02-28 ~ 2001-02-28 = 1 년 '상식'을 도약으로 확장 : 2000-02-29 ( 2000-02-28 이후 의 날 )에서 2001-02-28 = 0 년으로 . 나의 의견은 단지 답한 알고리즘 이 도약에 대한이 논리를 기대하고 동의한다면 항상 '올바른' 인간의 대답 을 준다고 언급했다.
— GitaarLAB

3
@RobG : 나는 나 또는 그 대답이 보편적으로 맞다고 말한 적이 없다 . 나는 문맥 / 관할권 / 관념에 대한 개념을 포함시켰다. 내 의견에는 대문자 IF (예외 도약 처리에 대한)가 명확하게 포함되어 있습니다. 사실, 나의 첫 번째 의견은 내가 말하고자하는 것을 정확하게 말했으며 옳고 그름에 대한 어떠한 판단도 포함하지 않았습니다. 실제로 내 의견은이 답변에서 무엇을 기대하지 않아야하는지 (그리고 왜) 왜 명확하지 않은지를 명확하게 설명합니다 ( '문제를 강조합니다'). 시 : 2 월 31 일?!?
— GitaarLAB

72

중요 :이 답변은 100 % 정확한 답변을 제공하지는 않으며 날짜에 따라 약 10-20 시간 정도 답변이 제공되지 않습니다.

더 나은 해결책은 없습니다 (어쨌든이 답변에는 없음). -나빈

물론 현재 받아 들여진 솔루션보다 더 빠르고 더 짧은 생일 계산기를 만들고자하는 충동에 저항 할 수 없었습니다. 내 솔루션의 주요 요점은 수학이 빠르므로 분기를 사용하는 대신 날짜 모델 javascript가 훌륭한 수학을 사용하여 솔루션을 계산할 수 있다는 것입니다

대답은 다음과 같으며 naveen의 것보다 ~ 65 % 더 빠릅니다.

function calcAge(dateString) {
  var birthday = +new Date(dateString);
  return ~~((Date.now() - birthday) / (31557600000));
}

매직 번호 : 31557600000은 24 * 3600 * 365.25 * 1000입니다. 이는 1 년의 길이이며, 1 년의 길이는 365 일이고 6 시간은 0.25 일입니다. 결국 i 층은 우리에게 최종 나이를 제공합니다.

벤치 마크는 다음과 같습니다. http://jsperf.com/birthday-calculation

OP의 데이터 형식을 지원하기 위해 교체 할 수 있습니다 +new Date(dateString);
로를+new Date(d.substr(0, 4), d.substr(4, 2)-1, d.substr(6, 2));

더 나은 솔루션을 만들 수 있다면 공유하십시오! :-)


정말 멋진 솔루션입니다. 내가 볼 수있는 유일한 문제 dateString는 Date () 생성자가 올바르게 구문 분석 할 수 있는 인수라는 것입니다. 예를 들어, YYYYMMDD내가 질문에 준 형식을 취 하면 실패합니다.
— Francisc

22
이 답변에는 버그가 있습니다. 시계를 오전 12시 1 분으로 설정하십시오. 오전 12:01에 calcAge ( '2012-03-27') (오늘 날짜)이면 1과 같아도 0이됩니다.이 버그는 오전 12시 전체에 존재합니다. 이는 1 년에 365.25 일이 있다는 잘못된 설명 때문입니다. 그렇지 않습니다. 우리는 지구 궤도의 길이가 아닌 달력 연도를 다루고 있습니다 (더 정확하게 365.256363 일입니다). 1 년은 365 일이며 윤년은 366 일입니다. 게다가, 이와 같은 성능은 의미가 없습니다. 유지 관리 성이 훨씬 중요합니다.
— Eric Brandel

1
귀하의 솔루션 Kristoffer에 감사드립니다. + new가 새로운 것과 비교했을 때, 그리고 두 개의 물결표 (~)가 반환되는 것을 물어볼 수 있습니까?
— Frank Jensen

1
@FrankJensen 안녕 프랭크, 나도 호기심이 답을 발견 : 이중 물결의 변환은 정수에 떠 인사말
— Stano

1
@FrankJensen은 물결표를 정수 (floored)로 변환하는 동안 물결표가 숫자 (2 진 값)를 반전 시키므로 물결표 2 개는 반올림 된 숫자를 제공합니다. new Date () 앞의 +는 객체를 날짜 객체의 정수 표현으로 변환합니다. 예를 들어 + '21 '=== 21
— Kristoffer Dorph

55

momentjs로 :

/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')

2
@RicardoPontual 여기에는 momentjs가 필요하므로 최고의 답변이 될 수 없습니다.
— itzmukeshy7

13
@ itzmukeshy7 실제로, 최고의 답변이 되려면 적어도 jQuery가 필요합니다.)
— thomaux

@thomaux 그것은 개발 환경에 전적으로 달려 있습니다!
— itzmukeshy7'10

@ itzmukeshy7이는 농담, 휴식)을 참조하십시오 meta.stackexchange.com/a/19492/173875
— thomaux

2
@thomaux 나는 그것이 농담임을 알았다;)
— itzmukeshy7

38

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

나는 각각 3.15576e + 10 밀리 초 (365.25 * 24 * 60 * 60 * 1000) 인 365.25 일 (윤년 ​​때문에 0.25) 년을 사용하고 있습니다.


1
아주 깔끔한-3.15576e + 10의 의미를 자세히 설명해 주시겠습니까?
— leonheess

1
예, 기능 앞에 다음 줄을 추가하는 것이 좋습니다.const yearInMs = 3.15576e+10 // Using a year of 365.25 days (because leap years)
— Lucas Janon

12

얼마 전에 나는 그 목적으로 기능을 만들었습니다.

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

Date 객체를 입력으로 사용하므로 'YYYYMMDD'형식화 된 날짜 문자열 을 구문 분석해야 합니다.

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

아 그래, 나는 윤년을 놓쳤다. 감사합니다.
— Francisc

1
선택한 날짜 조합에 대해 유효하지 않은 값을 제공합니다! (가) 예를 들어, birthDate인 월 5 일, 1980 , 현재 날짜 월 4 일, 2005 년 , 다음 함수는 잘못보고 age올바른 값은 24 인 ... 25로
— 브록 아담스

@BrockAdams 왜 이런가요? 현재이 문제가 있습니다. 감사.
— Jack H

가장자리 조건을 올바르게 처리하지 못하기 때문에 @VisionIncision. 믿거 나 말거나, 질문의 코드가 가장 좋은 접근 방법입니다. 나중에 답변 중 하나가 더 적합하게 다시 포장 된 것처럼 보일 수 있습니다.
— Brock Adams

CMS Hi :-) 나는이 질문 ( stackoverflow.com/questions/16435981/… )을 썼고 100 % 정확한 답변을 원하면 매년 확인해야한다고 들었습니다. 윤년이라면 마지막으로 계산하십시오. 분수. (구파의 답변 참조). 귀하의 기능 (일부) 은 그렇게 합니다. 그러나 어떻게 100 % 정확한 나이를 계산할 수 있습니까? DOB은 거의 1 / 1 / yyyy에서 거의 시작하지 않습니다. 그래서 ... 어떻게 당신의 func를 사용하여 정확한 나이를 계산할 수 있습니까?
— Royi Namir

10

내 해결책은 다음과 같습니다. 구문 분석 가능한 날짜를 입력하십시오.

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
}

7

다음과 같은 이유로 대체 솔루션 :

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

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

몇 달과 며칠 만에 나이를 쉽게 찾을 수 있습니다
— Sumit Kumar Gupta

5

생일이 이미 지 났는지 여부를 테스트하기 위해 도우미 함수를 정의합니다.이 함수 Date.prototype.getDoY는 연도의 일수를 효과적으로 반환합니다. 나머지는 설명이 필요 없습니다.

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

이로 인해 2 월 28 일 이후 생일의 경우 윤년으로 부정확 한 결과가 나타납니다. 그런 사람들의 나이는 1 일입니다. EG : DoB = 2001/07/04 의 경우이 함수는 2008/07/03 에서 7 년을 반환 합니다.
— Brock Adams

@ 브록 : 감사합니다. 내가 실수하지 않으면이 잘못된 행동을 수정했습니다.
— Marcel Korpel

그렇습니다, 나는 당신이 (엄격히 테스트하지 않고, 단지 분석 한 것 같습니다) 생각합니다. 그러나 새로운 솔루션은 OP 솔루션보다 간단하고 우아하지 않습니다 (이 솔루션이 함수에 올바르게 캡슐화되어 있다고 계산하지 않음). ... OP의 솔루션은 이해하기 쉽습니다 (따라서 감사, 테스트 또는 수정). 때로는 간단하고 간단합니다. IMO.
— Brock Adams

@Brock : 전적으로 동의합니다 :이 기능이 무엇을하는지 생각해야하며 결코 좋은 일이 아닙니다.
— Marcel Korpel

"if (doyNow <doyBirth)"가 "if (doyNow <= doyBirth)"가 아니어야합니까? 내 모든 테스트에서 하루는 하루가 지났고 고정되었습니다.
— 테드 Kulp

5

나는 그것이 단순히 그렇게 될 수 있다고 생각합니다 :

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

타임 스탬프와 함께 작동

age(403501000000)
//34

이 코드는 일년에 같은 나이의 사람을 계산합니다. 귀하의 예에서 오늘이 '09 / 19 / 2018 '인 경우 코드는 37을 제공하지만 나이 (생일 전날)는 36이됩니다.
— Steve Goossens

4

방금이 기능을 직접 작성해야했습니다. 허용 된 답변은 상당히 좋지만 IMO는 정리를 사용할 수 있습니다. 내 요구 사항 이었지만 문자열을 사용하도록 신속하게 조정할 수 있기 때문에 dob에는 유닉스 타임 스탬프가 필요합니다.

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

measureDays 함수에서 플랫 값 31을 사용했습니다. 모든 계산은 "일별"이 시간 소인을 단조 증가하는 척도라는 것입니다.

자바 스크립트 타임 스탬프 또는 문자열을 사용하는 경우 1000의 계수를 제거해야합니다.


n은 정의되어 있지 않습니다. 내 생각 엔 now.getFullYear ()
— Larry Battle

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

유럽 ​​날짜가 입력 된 연령을 얻으려면 :

getAge('16-03-1989')

stackoverflow.com/a/13367162/1055987에 대한 귀하의 제안에 감사드립니다 .
— JFK

3

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

2

나는 이전에 보여준 예제를 확인했으며 모든 경우에 작동하지는 않았으므로 이로 인해 나는 내 자신의 스크립트를 만들었습니다. 나는 이것을 테스트했으며 완벽하게 작동합니다.

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

2000-02-29에서 2001-02-28까지는 1 년이어야합니까? 그렇다면 위의 내용이 완벽하지 않습니다. :-)
— RobG

2

그것이 가장 우아한 방법입니다.

const getAge = (birthDateString) => {
  const today = new Date();
  const birthDate = new Date(birthDateString);

  const yearsDifference = today.getFullYear() - birthDate.getFullYear();

  if (
    today.getMonth() < birthDate.getMonth() ||
    (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
  ) {
    return yearsDifference - 1;
  }

  return yearsDifference;
};

console.log(getAge('2018-03-12'));


1

자바 스크립트로 생년월일로부터 나이 (년, 월, 일)를 가져옵니다

calcularEdad 함수 (년, 월, 일)

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

기능 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);
}

1

나를 위해 완벽하게 작동합니다.

getAge(birthday) {
    const millis = Date.now() - Date.parse(birthday);
    return new Date(millis).getFullYear() - 1970;
}

0

나는 이것이 매우 오래된 스레드라는 것을 알고 있지만 훨씬 더 정확한 나이를 찾기 위해 작성한이 구현에 넣고 싶었습니다.

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

물론 매개 변수를 얻는 다른 형식에 맞게이를 조정할 수 있습니다. 이것이 더 나은 솔루션을 찾는 데 도움이되기를 바랍니다.


0

나는 수학 대신 논리를 사용 하여이 접근법을 사용했습니다. 정확하고 빠릅니다. 매개 변수는 사람의 생일, 년 및 월입니다. 사람의 나이를 정수로 반환합니다.

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

OP에 따라 입력 할 문자열 또는 날짜 개체
— nazim

0

naveen 및 원래 OP의 게시물을 채택하여 문자열 및 / 또는 JS Date 객체를 모두 허용하는 재사용 가능한 메서드 스텁으로 끝났습니다.

gregorianAge()이 계산은 우리가 그레고리력을 사용하여 나이를 나타내는 방법을 정확하게 나타 내기 때문에 이름을 지정했습니다 . 즉, 월과 일이 출생 연도의 월과 일 이전 인 경우 종료 연도를 계산하지 않습니다.

/**
 * 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>


0

두 가지 옵션 더 :

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

0

나는 하나의 이전 답변으로 업데이트했습니다.

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

나는 그것이 도움이되기를 바랍니다 : D


0

나이를 계산하는 간단한 방법은 다음과 같습니다.

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

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

그것은 현재와 출생 연도 사이에 간단한 연도 차이를 나타냅니다. 오늘이 생일보다 연초가 빠르면 1 년을 뺍니다 (생각해 보면, 나이가 생일에 올라갑니다)
— Steve Goossens

0

당신은 당신의 형태로 나이 제한을 위해 이것을 사용할 수 있습니다-

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

0

나는 너무 늦었지만 이것이 생년월일을 계산하는 가장 간단한 방법이라는 것을 알았습니다.

$(document).ready(init);

function init()
{
  writeYears("myage", 0, Age());
  $(".captcha").click(function()
  {
    reloadCaptcha();
  });

}

function Age()
{
    var birthday = new Date(1997, 02, 01),  //Year, month, 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 );
    }
}

HTML 태그 :

<span id="myage"></span>

잘하면 이것이 도움이 될 것입니다.


-1

내가 얻을 수있는 가장 간단하고 정확한 솔루션은 다음과 같습니다.

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

다음은 2 월 29 일-> 2 월 28 일을 고려할 샘플입니다.

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

심지어 부정적인 나이에서도 작동합니다!


다른 모든 것과 마찬가지로 2000-02-29에서 2001-02-28까지는 0 년이라고 생각합니다.
— RobG

윤년 에지 사례를 수용하기 위해 답변을 업데이트했습니다. 감사합니다 @RobG
— wizulus

-1

또 다른 해결책 :

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

-1

로 momentjs "fromNow"방법이 형식의 날짜, 즉 함께 작업 할 수 있습니다 : 1968년 3월 15일

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

프로토 타입 버전

String.prototype.getAge = function() {
return moment(this.valueOf()).fromNow(true).replace(" years", "");

}

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.