除了时间之外,我还需要显示月份,日期和年份。
我尝试为月,日和年创建变量,然后按ID获取元素。我尝试执行此操作的示例:
var d = date.getDay();
var mn = date.getmonth();
var y = date.getFullYear();
编辑:这是我当前的代码。我也必须有一个时钟,但是我已经成功地对其进行了编码。
function showTime(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var session = "AM";
if(h == 0){
h = 12;
}
if(h > 12){
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
setTimeout(showTime, 1000);
}
showTime();
<div id="MyClockDisplay" class="clock"></div>
<div id="Month"></div>
<div id="Day"></div>
<div id="Years"></div>
答案 0 :(得分:1)
如果您遵循用于构建日期的用于构建时钟的相同模式,那么您走在正确的轨道上,但是您误解了某些JavaScript日期方法。 getDay()
返回一个星期几的数值(0代表星期日,等等),因此您需要使用getDate()
返回一个月的某天。另外,请注意,getMonth()
返回的月份索引从1月的0开始,因此在显示日期时必须进行调整。
您可以用更少的代码来完成相同的事情,但是以下示例遵循您的模式,因此希望您可以更轻松地遵循。
function showTime() {
var dt = new Date();
var d = dt.getDate();
var m = dt.getMonth() + 1; // getMonth() returns the month "index" starting with 0 for Jan
var y = dt.getFullYear();
var hh = dt.getHours();
var mm = dt.getMinutes();
var ss = dt.getSeconds();
var session = "AM";
if (hh == 0) {
hh = 12;
}
if (hh > 12) {
hh = hh - 12;
session = "PM";
}
d = (d < 10) ? "0" + d : d;
m = (m < 10) ? "0" + m : m;
hh = (hh < 10) ? "0" + hh : hh;
mm = (mm < 10) ? "0" + mm : mm;
ss = (ss < 10) ? "0" + ss : ss;
var date = m + "/" + d + "/" + y;
var time = hh + ":" + mm + ":" + ss + " " + session;
document.getElementById("myClockDisplay").textContent = time;
document.getElementById("myDateDisplay").textContent = date;
setTimeout(showTime, 1000);
}
showTime();
<div id="myClockDisplay" class="clock"></div>
<div id="myDateDisplay"></div>
答案 1 :(得分:-1)
请参阅下文。您的代码的工作副本。
<html>
<body onload='showTime()'>
<h1>Show a push button:</h1>
<form>
<div id="MyClockDisplay" class="clock"></div>
<div id="Month"></div>
<div id="Day"></div>
<div id="Years"></div>
</form>
<script>
function showTime(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var session = "AM";
if(h == 0){
h = 12;
}
if(h > 12){
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
// document.getElementById("MyClockDisplay").textContent = time;
setTimeout(showTime, 1000);
}