96's blog

WEBサイト制作科 6ヶ月コース

JavaScript06(Dateオブジェクト)

Dateオブジェクト(現在の日時を取得)

<script>
var now;
now = new Date();
document.write('<h1>',now.toString(),'</h1>');
</script>

Dateオブジェクト(指定した日時のオブジェクトを生成)

  • 日時指定でサイト表示させるときなどに使う。
<script>
var aDay;
aDay = new Date(2013,7,20,12,00,00);
document.write('<h1>',aDay.toString(),'</h1>');
</script>

Dateオブジェクト(日付を平成形式で表示)

  • 1月は0、2月は1、と数えていくため月の表示は+1させる。
<script>
var now,heisei,theDate;
now = new Date();
heisei = now.getFullYear() - 1988;
theDate = '平成' + heisei + '年' + (now.getMonth() + 1) + '月' + now.getDate() + '日';
now = new Date();
document.write('<h1>',theDate,'</h1>');
</script>

Dateオブジェクト(曜日を表示)

  • arrayを使い、取得した日時に応じて配列した曜日を表示させる。
<script>
var now,heisei,theDate;
var days = new Array('日','月','火','水','木','金','土');
now = new Date();
heisei = now.getFullYear() - 1988;
theDay =days[now.getDay()];
theDate ='平成' + heisei + '年' + (now.getMonth()+1) + '月' + now.getDate() + '日' + '(' + theDay + ')';
document.write('<h1>',theDate,'</h1>');
</script>

Dateオブジェクト(時間によってメッセージを変更)

  • 取得した日時に応じてメッセージや画像を変えることができる。
<script>
var today;
var hour;
today = new Date();
hour = today.getHours();

  document.write('<h1>');
if(hour<12){
  document.write('おはようございます');
}else if(hour<18){
  document.write('こんにちは');
}else if(hour<24){
  document.write('こんばんは');
}
document.write('</h1>');
</script>