39回目授業内容 オブジェクトを生成する(JavaScript)〜脱線
[授業][JavaScript]
オブジェクトを生成する
- Dateオブジェクト
<script> var now; now = new Date(); document.write('<h1>', now.toString(), '</h1>'); </script>
- 指定した日時のDateオブジェクトを生成
<script> var aDay; aDay = new Date(2014, 0, 11, 15, 55, 50); document.write('<h1>', aDay.toString(), '</h1>'); </script>
- Dateオブジェクトのメソッド
- 月数を表す場合PC的に「0」が1月になるため「+ 1」を入力する
<script> var now, date; now = new Date(); date = now.getFullYear() + '年' + (now.getMonth() + 1) + '月' + now.getDate() +'日' + now.getHours() + '時' + now.getMinutes() + '分'; document.write(date); </script>
- getTimeメソッドで日数の差を求める
<script> var now, date; now = new Date(); var gantan, days, diff; gantan = new Date(now.getFullYear() + 1, 0, 1); diff = gantan.getTime() - now.getTime(); days = Math.ceil(diff / (24 * 60 * 60 * 1000)); document.write('<h1>今年は残り日数:' + days ,'</h1>'); </script>
- 日時時刻の設定
<script> var now, hour, minute; now = new Date(); hour = now.getHours(); minute = now.getMinutes(); document.write('<h1>'); document.write('現在時刻:'); document.write(hour, '時', minute, '分'); document.write('</h1>'); </script>
- Mathオブジェクト
- randomメソッド
<script> var random = Math.random(); if(random < 0.33) { document.write('<h1>', '大吉', '</h1>'); }else if(random < 0.66) { document.write('<h1>', '中吉', '</h1>'); }else{ document.write('<h1>', '凶', '</h1>'); } </script>