如何使用javascript显示日期?

时间:2015-06-04 04:29:12

标签: javascript

当我尝试下面的javascript代码来显示日期

<!DOCTYPE html>
<html>
<body>
<h1> javascript</h1>
<button type="button" onclick=document.getElementById('demo').innerHTML=Date()">click me to display date and time.</button>
<p id="demo"></p>
</body>
</html>

4 个答案:

答案 0 :(得分:4)

几乎没有更正:

&#13;
&#13;
<!DOCTYPE html>
<html>

<body>
  <h1> javascript</h1>
  <!-- added missing qoutes for onclick -->
  <button type="button" onclick="document.getElementById('demo').innerHTML= new Date();">click me to display date and time.</button>
  <!-- added missing, new keyword for Date() -->
  <p id="demo"></p>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

以下代码将有所帮助......

var date = new Date();
var n = date.toDateString();
var time = date.toLocaleTimeString();

alert(n + ' ' + time);

你甚至可以根据需要将它放在HTML DIV标签中

JS

document.getElementById('time').innerHTML = n + ' ' + time;

HTML

<div id='time'></div>

答案 2 :(得分:0)

onclick=document.getElementById('demo').innerHTML=Date()">click me to display

这需要修复。当您撰写onclick=时,您开始时没有"。 简单修复,添加它:

onclick="document.getElementById('demo').innerHTML=Date()">click me to display

工作修复: https://jsfiddle.net/4cjhg2uo/

答案 3 :(得分:0)

您错过了onclick =&#34; ...&#34;

中的引号
<!DOCTYPE html>
<html>
<body>
<h1> javascript</h1>
<button type="button" onclick="document.getElementById('demo').innerHTML=Date()">click me to display date and time.</button>
<p id="demo"></p>
</body>
</html>