JavaScript Dateオブジェクト 残日数を表示する。
本日はJavaScriptで、Dateオブジェクトを使用し、残日数を表示させたいと思います。
【前提】
getFullYear():年を取り出す
getMonth():月を取り出す
getDate(): 日を取り出す
getDay(): 曜日を取り出す
getHours():時を取り出す
getMinutes():分を取り出す
getSeconds():秒を取り出す
【使用するオブジェクト】
new Date();
→パラメーター無しの場合、現在の日付、時刻のオブジェクトを作成します。
1.今年の残りの日数を表示する。
<表示結果>
今年の残り日数252
<!DOCTYPE html>
<html lang='ja'>
<head>
<meta charset='UTF-8'>
<title>Dateオブジェクトのメソッドを使う</title>
</head>
<body>
<script>
var now,date;
now=new Date();
var gantan,days,diff;
gantan = new Date(now.getFullYear()+1,0,1);
/*→来年の1月1日をあらわすDateオブジェクトを生成、+1して来年を設定、0は1月、1日*/
diff = gantan.getTime() - now.getTime();
/*来年の1月1日と現在時刻の時間差をミリ単位で求める*/
days = Math.ceil(diff / (24*60*60*1000));<!--Math.ceilは切り上げ-->
/*秒を日数に換算し小数点以下を切り上げる*/
document.write('<h1> 今年の残り日数'+ days+ '</h1>');
</script>
</body>
</html>
2.指定した日付までの残日数を表示する。
<表示結果>
私の次の誕生日までの残りに日数は256
※今回は、誕生日を1月5日に設定します。
<!DOCTYPE html>
<html lang='ja'>
<head>
<meta charset='UTF-8'>
<title>自分の次の誕生日までの日数</title>
</head>
<body>
<script>
var now,date;
now=new Date();
var gantan,days,diff;
gantan = new Date(now.getFullYear()+1,0,5);
/*来年なので、+1、0は1月、5日*/
diff = gantan.getTime() - now.getTime();
/*来年の1月1日と現在時刻の時間差をミリ単位で求める*/
days = Math.ceil(diff / (24*60*60*1000));
/*秒を日数に換算し小数点以下を切り上げる*/
<!--Math.ceilは切り上げ 日付単位でのカウント方法-->
document.write('<h1> 私の次の誕生日までの残り日数は'+ days+ '</h1>');
</script>
</body>
</html>