年月から生年月日を計算する
何歳と何か月ですか?
以下が実際のプログラムになります。このプログラムでは、入力した年齢から生年月日を計算して表示します。
```
<!DOCTYPE html>
<html>
<head>
<title>年月から生年月日を計算する</title>
</head>
<body>
<h1>年月から生年月日を計算する</h1>
<p>何歳と何か月ですか?</p>
<form>
<label for="age">年齢:</label>
<input type="number" id="age" name="age">
<label for="month">月:</label>
<input type="number" id="month" name="month">
<button type="button" onclick="calculateBirth()">計算</button>
</form>
<div id="result"></div>
<script>
function calculateBirth() {
let age = document.getElementById("age").value;
let month = document.getElementById("month").value;
let now = new Date();
let birthYear = now.getFullYear() - age;
let birthMonth = now.getMonth() + 1 - month; // 月は0から始まるので1を足す
if (birthMonth < 1) { // 月がマイナスになった場合は1年戻す
birthYear--;
birthMonth += 12;
}
let resultDiv = document.getElementById("result");
resultDiv.innerHTML = birthYear + "年" + birthMonth + "月生まれです。";
}
</script>
</body>
</html>
```
ジョークとしては、「年齢を入力しなくても、このプログラムが勝手に計算してあなたの生年月日を特定してしまうということです!」というものがありますが、セキュリティ上の問題があるため今回は取り入れませんでした。