LoginSignup
0
0

More than 3 years have passed since last update.

JavaScriptで現在日時を表示させてみた

Posted at

JavaScriptで現在日時を表示するコードを書いたのでメモ程度に残しておきます。

とりあえず雛形の作成から

ターミナル
$ mkdir clock
$ cd clock
$ touch index.html

作成したhtmlファイルに以下を追記

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>clock</title>
  </head>

  <body>
    <div id="clock"></div>
  </body>
</html>

これで雛形が完成したのでjavascriptを書いていきます。

以下のコードを<div id="clock"></div>の下に記載してください。

index.html
<script>
  timerID = setInterval('clock()', 500);

    function clock() {
      document.getElementById("clock").innerHTML = getNow();
    }

    function getNow() {
      var now = new Date();
      var year = now.getFullYear();
      var mon = now.getMonth() + 1;
      var day = now.getDate();
      var hour = now.getHours();
      var min = now.getMinutes();
      var sec = now.getSeconds();

      var s = year + "" + mon + "" + day + "" + hour + "" + min + "" + sec + "";
      return s;
    }
</script>

これでindex.htmlを実行すると現在日時が表示できます。

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