我制作了一个具有输入日期输入和年龄输入的反应成分,可以在数年,数月和数天内输入。
因此,如果输入年龄,我想获得该人的出生日期。
例如, 年龄为年= 24,月数= 1,天数= 15 所以出生日期应该是18-04-1993 ..
这是我到目前为止所做的事情。但是,如果(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}`;
提前致谢。
答案 0 :(得分:1)
如果您不想按照上面的评论中的建议使用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));
答案 1 :(得分:0)
在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() );