无法使用javascript获取当前时间

时间:2017-12-22 12:42:35

标签: javascript

仅显示今天的日期无法获得时间。

<script type="text/javascript">
n =  new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
</script>

<li id="date"></li>

2 个答案:

答案 0 :(得分:0)

您需要添加代码以提取小时,分钟和秒,然后将它们附加到字符串。见下文。

&#13;
&#13;
n =  new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
hour = n.getHours();
min = n.getMinutes();
sec = n.getSeconds();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y + ' ' + hour + ':' + min + ':' + sec ;
&#13;
<li id="date"></li>
&#13;
&#13;
&#13;

答案 1 :(得分:-2)

您的代码是完整的,但您没有检查运行时问题。

如果你在声明div之后运行你的js代码就行了。 因为,javascript搜索后没有在dom上退出的id。如果更改代码类型,将删除运行时问题。 Plunker Example

<li id="date"></li>    
<script type="text/javascript">
n =  new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
</script>

Problem Solution 2

如果你想要你可以使用日期/时间的时刻存储它非常有用。 Moment JS Libary