Home  >  Article  >  Web Front-end  >  JavaScript page displays current time instance code in real time

JavaScript page displays current time instance code in real time

高洛峰
高洛峰Original
2016-12-09 13:10:55923browse

Foreword

This time I carefully read the relevant content again, and now I summarize the points that need to be paid attention to as follows:

1. The number of weeks obtained through getDay() starts from 0, 0 means Sunday, and then starts from 1~ 6 means Monday to Saturday in turn;

2. To get the date, you need to use getDate() instead of getDay(), because you may habitually think that the date is the number of days, and you may use getDay(), but in fact getDay() is used For getting the number of weeks;

3. Get the month through getMonth(), counting starts from 0, so you need to add 1.

The example code is as follows:

<html>
<head>
  <title></title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <link rel="stylesheet" type="text/css" href="">
  <script type="text/javascript"></script>
  <style type="text/css">
    input{
      width: 200px;
    }
  </style>
</head>
<body>
  <input id="input">
  <script type="text/javascript">
    var in_1 = document.getElementById(&#39;input&#39;);
    function showTime(){
      var date = new Date();
      var week = date.getDay();
      var weekday;
      switch(week){
        case 0: weekday = &#39;星期天&#39;;break;
        case 1: weekday = &#39;星期一&#39;;break;
        case 2: weekday = &#39;星期二&#39;;break;
        case 3: weekday = &#39;星期三&#39;;break;
        case 4: weekday = &#39;星期四&#39;;break;
        case 5: weekday = &#39;星期五&#39;;break;
        case 6: weekday = &#39;星期六&#39;;break;
      }
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();
      var in_1 = document.getElementById(&#39;input&#39;);
      in_1.value = year + &#39;年&#39; + month + "月" + day + &#39;日&#39;+&#39; &#39; + weekday + &#39; &#39; + hour + &#39;:&#39; + minute + &#39;:&#39; + second;
      setTimeout(showTime,1000);
    }
    showTime();
  </script>
</body>
</html>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn