LoginSignup
0
0

More than 3 years have passed since last update.

【Javascript初歩】Dateオブジェクトを使って年月日表示ボタンを作成する

Posted at

ブラウザ上に、現在の年月日を表示する方法を備忘として残しておきます。

Dateオブジェクトとは

Dateオブジェクトとは、日付や時間などを扱うメソッドがすでに定義されているもので、時間の計算や日付の換算等を簡単に行うことができる。

一例

・現在の日付、時刻のオブジェクトを作成

 let now = new Date();

・西暦年を取得

 let year = now.getFullYear();

・月を取得(※0~11の数字で取得するため、+1すること!)

 let month = now.getMonth() + 1;

・日付を取得

 let day = now.getDate();

活用例 -クリックすると今日の年月日が表示されるボタンの作成-

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>年月日表示</title>
</head>
<body>
  <h1 id="select">年月日表示</h1>
  <input type="button" value="Click" onclick="change()"> <!--onclick・・・クリック時にメソッドを呼び出す-->
  <script>
    function today(){
      let union = null; //年・月・日を結合するための変数をnullで設定。
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth()+1; //0月から始まるため、1を加算している。
      let day = now.getDate();
      return union = year+""+month+""+day+"";
    }
      let expressToday = today();

    const change = function(){
          const ymd = document.getElementById('select');
          ymd.innerHTML = expressToday; //取得した要素のうち、html要素を書き換える。
        }
  </script>
</body>
</html>

プレビュー

qiita_js_ymd.gif

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0