入力した目標日までの日数を表示させるHTMLとJavaScriptのコード
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>日数カウンター</title>
<style>
#targetDate {
font-size: 3em;
height: 3em;
}
#countdown {
font-size: 3em;
}
</style>
</head>
<body>
<form>
<label for="targetDate">目標日(8桁の数字):</label>
<input type="text" id="targetDate" name="targetDate" size="8">
<button type="button" onclick="countdown()">あと何日</button>
</form>
<p id="countdown"></p>
<script>
function countdown() {
// 目標日付を取得する
const targetDateInput = document.getElementById("targetDate");
const targetDate = targetDateInput.value;
// 入力値のチェック
if (!/^\d{8}$/.test(targetDate)) {
alert("8桁の数字で入力してください");
return;
}
// 今日の日付を取得する
const today = new Date();
// 目標日付を日付オブジェクトに変換する
const year = parseInt(targetDate / 10000);
const month = parseInt((targetDate % 10000) / 100) - 1;
const day = targetDate % 100;
const target = new Date(year, month, day);
// 残り日数を計算する
const diff = target.getTime() - today.getTime();
const daysLeft = Math.ceil(diff / (1000 * 60 * 60 * 24));
// 残り日数を表示する
const countdown = document.getElementById("countdown");
countdown.innerHTML = `目標日まであと${daysLeft}日`;
}
</script>
</body>
</html>
この記事が気に入ったらサポートをしてみませんか?