繁体   English   中英

以年,月和日表示的从年龄获取出生日期的逻辑

[英]Logic to get Date Of Birth From Age expressed in years months and days

我正在制作一个反应组件,该组件具有出生日期输入和年龄输入,需要输入年,月和日。

因此,如果要输入年龄,我想获取该人的出生日期。

例如,年龄是年= 24,月= 1,天= 15因此,出生日期应为1993年4月18日。

这是我到目前为止所做的。.但是逻辑在if(nowDay <= ageDay)块处中断。

const now = new Date();
const nowDay = now.getDate();
const nowMonth = now.getMonth() + 1;
const nowYear = now.getFullYear();
const ageYear = ReactDOM.findDOMNode(this.yearInput).value;
const ageMonth = ReactDOM.findDOMNode(this.monthInput).value;
const ageDay = ReactDOM.findDOMNode(this.daysInput).value;
let dobYear = nowYear - ageYear;
let dobMonth = nowMonth - ageMonth;
let dobDay = nowDay - ageDay;
if (dobMonth <= 0) {
  dobYear --;
  dobMonth = (12 + dobMonth);
}
if (ageMonth > 12) {
  dobYear = dobYear + Math.floor(dobMonth / 12);
  console.log('ASIJASOIJAS', dobYear); // eslint-disable-line
  dobMonth = ageMonth % 12;
}
if (nowDay <= ageDay) {
  dobMonth -= Math.floor(ageDay / 30);
  dobDay = ageDay % 30;
  if (dobMonth < 0) {
    dobYear = dobYear - (dobMonth % 12) - 1;
    dobMonth = 12 - (dobMonth % 12);
    dobDay ++;
  }
}
const age = {
  days: ageDay,
  months: ageMonth,
  years: ageYear,
};
const month = dobMonth < 10 ? `0${dobMonth}` : dobMonth;
const day = dobDay < 10 ? `0${dobDay}` : dobDay;
dateOfBirth = `${dobYear}-${month}-${day}`;

提前致谢。

如果您不想按照上面的注释中的建议使用momentjs ,则可以使用像这样的简单函数来解决问题。 请注意,它返回一个Date对象,因此您必须将其格式化为所需的任何字符串格式。

 const getBirthDateFromAge = (ageYears, ageMonths, ageDays) => { const date = new Date(); date.setFullYear(date.getFullYear() - ageYears); date.setMonth(date.getMonth() - ageMonths); date.setDate(date.getDate() - ageDays); return date; }; console.log(getBirthDateFromAge(10, 9, 4)); 

在nodejs es6中:

 const leapyear = ( year ) => { return year % 100 === 0 ? year % 400 === 0 : year % 4 === 0; } const countDaysByYears = ( year ) => { let currentYear = new Date().getFullYear(); let count = 0; while ( year != 0 ) { if ( leapyear( currentYear ) ) count++; year -= 1; currentYear -= 1; } return count; } const getMyDoB = ( years, months, days ) => { months = ( months / 12 ); days = ( ( days + countDaysByYears( years ) ) / 365 ); var ageInYears = years + months + days; var ageInMillis = ageInYears * 365 * 24 * 60 * 60 * 1000; return new Date( Date.now() - ageInMillis ); } console.log( getMyDoB( 31, 7, 19 ).toDateString() ); console.log( getMyDoB( 25, 0, 24 ).toDateString() ); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM