gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:34:58 25 4
gpt4 key购买 nike

我正在制作一个 react 组件,它具有出生日期输入和年龄输入,以年、月和日为单位输入。

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

例如, 年龄为年 = 24,月 = 1,天 = 15所以出生日期应该是 18-04-1993..

这是我到目前为止所做的...但是逻辑在 if (nowDay <= AgeDay) block 处被破坏了..

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

关于javascript - 从年龄获取出生日期的逻辑以年月日表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44342188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com