javascript - 想要根据给定的年龄计算出生日期

标签 javascript html

我正在尝试根据给定的年龄计算出生日期。 我的逻辑是

当我们进入一个年龄时说“5”。出生日期将按当前日期起 5 年计算。示例当前日期为 20/8/2018。 如果年龄为 5,那么出生日期将为 20/8/2013。 下面是我的代码:

function validatedob() {
  var dob_value = document.getElementById('dob').value;
  var age_value = document.getElementById('age').value;
  var current_date = new Date();
  var birth_date = new Date();
  var birth_year = current_date.getFullYear() - age_value;
  var birth_month = current_date.getMonth();
  var birth_day = current_date.getDate();

  birth_date.setDate(current_date.getFullYear() - age_value);
  birth_date.setMonth(current_date.getMonth());
  birth_date.setFullYear(current_date.getDate());

  document.getElementById('dob').setDate(birth_day);
  document.getElementById('dob').setMonth(birth_month);
  document.getElementById('dob').setFullYear(birth_year);
}
<div class="form-inline" id="Age">
  <label for="age">Age</label>
  <input id="age" type="integer" name="age" onchange="validatedob()">
</div>

<div class="form-inline" id="birth">
  <label for="DOB">Date of Birth</label>
  <input id="dob" type="date" value="Unknown" name="date_of_birth" max="31-12-2030">
</div>

这不起作用。我不擅长 html 属性。 有人能帮我吗?如何实现这一目标?

最佳答案

这是简单的答案:

> d1 = new Date(2018, 00, 01)
Date 2018-01-01T00:00:00.000Z
> d2 = new Date(d1.getFullYear() - 5, d1.getMonth(), d1.getDate())
Date 2013-01-01T00:00:00.000Z

但是,我建议使用诸如 Luxon 之类的库.

如果您自己操作,日期操作绝对是一场噩梦。来自 Computerphile 的这段视频比我更好地总结了它:
https://www.youtube.com/watch?v=-5wpm-gesOY

关于javascript - 想要根据给定的年龄计算出生日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51933776/

相关文章:

javascript - TableTools 示例的基本用法不起作用

javascript - 回溯 JavaScript 源代码中的表达式

javascript - 排序后再次添加已删除的 DataTable 行

document.write() 的 JavaScript 替代方案

html - CSS/HTML 黄框不出现

javascript - 如何在javascript中使用MD5传输密码

javascript - 如果我的用户有 ie6 该怎么办

javascript - 如何在 Promise 中捕获未捕获的异常

javascript - 在我的网站内打开外部链接

javascript - 尝试将相同的背景固定到伪元素时遇到麻烦