Dateオブジェクトによる現在時刻の取得と表示
JavaScriptのDateオブジェクトを活用してシステム時間の操作を行う際、以下のメソッドが主に利用されます。
new Date():システムの現在時刻を取得getFullYear():年を取得getMonth() + 1:月(0~11のため+1が必要)getDate():日付getDay():曜日(0=日曜日~6=土曜日)getHours()、getMinutes()、getSeconds():時、分、秒
以下の実装例では、リアルタイムで時刻を更新する処理を構築しています。
<html>
<head>
<title>リアルタイム時計</title>
<meta charset="UTF-8">
<script>
window.onload = () => {
setInterval(updateClock, 1000);
updateClock();
function updateClock() {
const current = new Date();
const weekNames = ['日', '月', '火', '水', '木', '金', '土'];
const formatted = `${current.getFullYear()}年${current.getMonth()+1}月${current.getDate()}日 ${weekNames[current.getDay()]} ${padZero(current.getHours())}:${padZero(current.getMinutes())}:${padZero(current.getSeconds())}`;
document.body.innerHTML = formatted;
}
function padZero(num) {
return num < 10 ? `0${num}` : String(num);
}
};
</script>
</head>
<body>
</body>
</html>倒計時機能の実装原理
倒計時機能は、現在時刻と目標時刻の差分を計算し、日・時・分・秒に変換して表示します。以下の例では、2018年5月1日(5月は0-basedで4)を目標時刻として設定しています。
<html>
<head>
<meta charset="UTF-8">
<title>倒計時機能</title>
<script>
window.onload = () => {
let intervalId;
const target = new Date(2018, 4, 1, 0, 0, 0);
function calculateRemaining() {
const now = new Date();
const diff = Math.floor((target - now) / 1000);
if (diff <= 0) {
clearInterval(intervalId);
document.body.innerHTML = '目標日時を過ぎました';
return;
}
const days = Math.floor(diff / 86400);
const hours = Math.floor((diff % 86400) / 3600);
const minutes = Math.floor((diff % 3600) / 60);
const seconds = diff % 60;
const display = `2018年5月1日まで残り:${padZero(days)}日 ${padZero(hours)}時間 ${padZero(minutes)}分 ${padZero(seconds)}秒`;
document.body.innerHTML = display;
}
function padZero(value) {
return value < 10 ? `0${value}` : String(value);
}
intervalId = setInterval(calculateRemaining, 1000);
calculateRemaining();
};
</script>
</head>
<body>
</body>
</html>