Add a span element and update its text content.
添加SPAN元素并更新其文本内容。
var span = document.getElementById('span');
function time() {
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes();
var h = d.getHours();
span.textContent =
("0" + h).substr(-2) + ":" + ("0" + m).substr(-2) + ":" + ("0" + s).substr(-2);
}
setInterval(time, 1000);
<span id="span"></span>
Answer updated [2022] https://stackoverflow.com/a/67149791/7942242
答案更新[2022] https://stackoverflow.com/a/67149791/7942242
You can also use toLocaleTimeString() on Date() to just get your display date instead of creating through so many variables.
您还可以在Date()上使用toLocaleTimeString()来只获取显示日期,而不是通过这么多变量进行创建。
window.onload = displayClock();
function displayClock(){
var display = new Date().toLocaleTimeString();
document.body.innerHTML = display;
setTimeout(displayClock, 1000);
}
Use new Date().toLocaleTimeString()
within the setInterval function.
在setInterval函数中使用new date().toLocaleTimeString()。
setInterval(() => console.log(new Date().toLocaleTimeString()),1000);
Here's my answer, hope it may help.
这是我的答案,希望能有所帮助。
<html>
<body>
<script type="text/javascript" charset="utf-8">
let a;
let time;
setInterval(() => {
a = new Date();
time = a.getHours() + ':' + a.getMinutes() + ':' + a.getSeconds();
document.getElementById('time').innerHTML = time;
}, 1000);
</script>
<span id="time"></span>
</body>
</html>
I have used the setInterval
arrow function and declared the variables a
, time
outside so as to avoid repeated allocation, where the span id(time) runs for a specified interval(here it is 1000) and document.getElementById("time")
call gets you the element by the specified ID and also it's setting the innerHTML
of that element to the value of time
.
我使用了setInterval箭头函数,并在外部声明了变量a,time,以避免重复分配,其中span id(time)在指定的时间间隔内运行(这里是1000),document.getElementById(“time”)调用通过指定的ID获取元素,并将该元素的innerHTML设置为time值。
Please follow this link https://codepen.io/uniqname/pen/eIApt you will get your desire clock or try this code
请点击此链接https://codepen.io/uniqname/pen/eIApt,您将获得您想要的时钟或尝试此代码
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
Code will display clock in digital format
代码将以数字格式显示时钟
function myClock() {
setTimeout(function() {
const d = new Date();
const n = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = n;
myClock();
}, 1000)
}
myClock();
<html>
<body>
<div id="demo"></div>
</body>
</html>
This can be nicely done using ES6.
使用ES6可以很好地实现这一点。
const clock12 = document.getElementById('clock12')
const clock24 = document.getElementById('clock24')
// Concatenate a zero to the left of every single digit time frame
function concatZero(timeFrame) {
return timeFrame < 10 ? '0'.concat(timeFrame) : timeFrame
}
function realTime() {
let date = new Date()
let sec = date.getSeconds()
let mon = date.getMinutes()
let hr = date.getHours()
// 12 hour time
// If the hour equals 0 or 12, the remainder equals 0, so output 12 instead. (0 || 12 = 12)
clock12.textContent = `${concatZero((hr % 12) || 12)} : ${concatZero(mon)} : ${concatZero(sec)} ${hr >= 12 ? 'PM' : 'AM'}`
// 24 hour time
clock24.textContent = `${concatZero(hr)} : ${concatZero(mon)} : ${concatZero(sec)}`
}
setInterval(realTime, 1000)
body,
html {
height: 100%;
display: grid;
}
div {
margin: auto;
font-size: 2rem;
font-family: consolas;
}
<div>
<p id="clock12"></p>
<p id="clock24"></p>
</div>
If this is the root of your problem
如果这是你问题的根源
But instead of replacing the current time of day it prints a new time of day every second.
then you can't make the Date object responsive, because
那么你就不能让Date对象响应,因为
JavaScript Date objects represent a single moment in time in a platform-independent format.
If you don't wish to create a new object every second, you can register a dedicated Web worker that calls performance.now() every second, but this is more demanding on system resources than simply creating the Date object, which just copies the actual system clock (thus not creating a separate process for measuring the time). tl;dr: just create a new Date object every second as you do.
如果您不想每秒创建一个新对象,可以注册一个专用的Web Worker,它每秒调用Performance.Now(),但与简单地创建Date对象相比,这对系统资源要求更高,后者只复制实际的系统时钟(因此不会创建单独的进程来测量时间)。TL;DR:只需按照您所做的那样,每秒创建一个新的Date对象。
The root of your document.write()
issue stems from this:
您的Document.write()问题的根源是这样的:
Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document [in setInterval in your case] automatically calls document.open(), which will clear the document.
To update part of your page, you usually set innerHTML of some element as @Pranav suggests.
要更新页面的一部分,通常需要按照@Pranav的建议设置某些元素的innerHTML。
<html>
<head>
<script>
function clock() {
var clockDiv = document.querySelector("#clock");
return setInterval(() => {
let date = new Date();
let tick = date.toLocaleTimeString();
clockDiv.textContent = tick;
}, 1000);
}
</script>
</head>
<body onload="clock()">
<div id="clock"></div>
</body>
</html>
Also keep in mind that the code isn't loaded exactly at the turn of a second plus there's a small natural drift. So if you care about the exact seconds you also need to keep it at sync.
还要记住,代码并不是在一秒钟的转折点加载的,还有一个很小的自然漂移。因此,如果你关心准确的秒数,你也需要保持同步。
Here's an example continuing on yusrasyed's answer from above:
以下是yusrased上面的回答的一个继续的例子:
window.onload = displayClock();
function displayClock(){
const d = new Date();
var sync = d.getMilliseconds();
var syncedTimeout = 1000 - sync;
var display = d.toLocaleTimeString();
document.body.innerHTML = display;
setTimeout(displayClock, syncedTimeout);
}
setInterval(function () {
const time = new Date().toTimeString().slice(0, 8);
span.textContent = time
}, 1000)
<span id="span"></span>
A working demo, follow the link
一个有效的演示,请点击链接
http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
Http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
Updated
you are using document.write which appends the current time each time (and that's what your problem was if I am not wrong).
So for replacing previous time with new time -
1. you have to open document with replace mode (as shown in code below)
2. you write the current time
3. then you close the document.
更新您使用的是Document.WRITE,它每次都会附加当前时间(如果我没有错,这就是您的问题所在)。所以要用新时间替换以前的时间-1.你必须用替换模式打开文档(如下面的代码所示)2.你写下当前时间3.然后关闭文档。
function time(){
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes();
var h = d.getHours();
document.open("text/html", "replace");
document.write(h + ":" + m + ":" + s);
document.close();
}
setInterval(time,1000);
anyone wanting to know how to code a digital clock with alarm? Here is my codepen http://codepen.io/abhilashn/pen/ZLgXbW
有人想知道如何编码一个带闹钟的数字时钟吗?这是我的代码页http://codepen.io/abhilashn/pen/ZLgXbW
function AmazeTime(almbtnobj) {
this.date,this.day,this.dt,this.month, this.year,this.hour,this.minute,this.second = null;
this.almHour, this.almMinute, almMeridiem = null;
this.meridiem = "AM";
this.almBtn = almbtnobj;
this.almBtn = this.setAlarm;
}
AmazeTime.prototype.initializeTime = function() {
this.dt = new Date();
this.day = this.getDayInWords(this.dt.getDay());
this.date = this.dt.getDate();
this.month = this.getMonthInShort(this.dt.getMonth());
this.year = this.dt.getFullYear();
this.hour = this.setHour(this.dt.getHours());
this.minute = this.doubleDigit(this.dt.getMinutes());
this.second = this.doubleDigit(this.dt.getSeconds());
this.meridiem = this.setMeridiem(this.dt.getHours());
}
AmazeTime.prototype.setHour = function(hr) {
if(hr > 12) {
hr = hr - 12;
}
if(hr === 0) {
hr = 12;
}
return this.doubleDigit(hr);
}
AmazeTime.prototype.doubleDigit = function(val) {
if(val < 10) {
val = "0" + val;
}
return val;
}
AmazeTime.prototype.setMeridiem = function(hr) {
if(hr > 12) {
hr = hr - 12;
return "PM";
} else {
return "AM";
}
}
AmazeTime.prototype.getMonthInShort = function(value) {
switch(value) {
case 0:
return "Jan";
break;
case 1:
return "Feb";
break;
case 2:
return "Mar";
break;
case 3:
return "Apr";
break;
case 4:
return "May";
break;
case 5:
return "Jun";
break;
case 6:
return "Jul";
break;
case 7:
return "Aug";
break;
case 8:
return "Sep";
break;
case 9:
return "Oct";
break;
case 10:
return "Nov";
break;
case 11:
return "Dec";
break; }
}
AmazeTime.prototype.getDayInWords = function(value) {
switch(value) {
case 0:
return "Sunday";
break;
case 1:
return "Monday";
break;
case 2:
return "Tuesday";
break;
case 3:
return "Wednesday";
break;
case 4:
return "Thursday";
break;
case 5:
return "Friday";
break;
case 6:
return "Saturday";
break;
}
}
AmazeTime.prototype.setClock = function() {
var clockDiv = document.getElementById("clock");
var dayDiv = document.getElementById("day");
var dateDiv = document.getElementById("date");
var self = this;
dayDiv.innerText = this.day;
dateDiv.innerText = this.date + " " + this.month + " " + this.year;
clockDiv.innerHTML = "<span id='currentHr'>" + this.hour + "</span>:<span id='currentMin'>" + this.minute + "</span>:" + this.second + " <span id='meridiem'>" + this.meridiem + "</span>";
}
AmazeTime.prototype.setAlarm = function() {
this.almHour = this.doubleDigit(document.getElementById('almHour').value);
this.almMinute = this.doubleDigit(document.getElementById('almMin').value);
if(document.getElementById("am").checked == true) {
this.almMeridiem = "AM";
} else {
this.almMeridiem = "PM";
}
}
AmazeTime.prototype.checkAlarm = function() {
var audio = new Audio('http://abhilash.site44.com/images/codepen/audio/audio.mp3');
if(this.hour == this.almHour && this.minute == this.almMinute && this.almMeridiem == this.meridiem) {
audio.play();
if(this.minute > this.almMinute) {
audio.pause();
}
}
}
var mytime = null;
mytime = new AmazeTime(document.getElementById("savebtn"));
window.addEventListener('load', function() {
function runTime() {
mytime.initializeTime();
mytime.setClock();
mytime.checkAlarm();
}
setInterval(runTime, 1000);
} , false);
function saveAlarm() {
mytime.setAlarm();
$('#myModal').modal('hide');
}
document.getElementById("savebtn").addEventListener("click", saveAlarm , false);
body { background:#A3ABF2; font-family:Arial; text-align:center; }
.day { font-size:64px; }
.date { font-size:33px; }
.clock { font-size:44px; }
.clock-content { margin-top:35vh; color:#FFF; }
.alarm-icon { font-size:34px; cursor:pointer; position:absolute; top:15px; right:15px; color:#FFF; }
.setalmlbl { padding-right:20px; }
.setalmtxtbox { margin-right:10px; width:60px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<i id="alarmbtn" data-toggle="modal" data-target="#myModal" class="fa fa-bell alarm-icon"></i>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"> Set Alarm</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form>
<div class="modal-body">
<div class="form-inline">
<label for="hours" class="setalmlbl" >Hours </label>
<select class="form-control setalmtxtbox" name="almHour" id="almHour">
<script>
for(var h = 1; h <= 12; h ++) {
document.write("<option value="+ h +">" + h + "</option>");
}
</script>
</select>
<label for="minutes" class="setalmlbl"> Minutes </label>
<select class="form-control setalmtxtbox" name="almMin" id="almMin">
<script>
for(var m = 1; m <= 60; m++) {
document.write("<option value="+ m +">" + m + "</option>");
}
</script>
</select>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="meridiem" id="am" value="am" checked>
A.M.
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="meridiem" id="pm" value="pm">
P.M.
</label>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="savebtn" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="clock-content">
<div class="day" id="day"></div>
<div class="date" id="date"></div>
<div class="clock" id="clock"></div>
</div>
</div>
you can look at this simple javascript clock here in app.js for a live clock in the browser https://github.com/danielrussellLA/simpleClock
您可以在app.js中查看这个简单的Java脚本时钟,以获得浏览器https://github.com/danielrussellLA/simpleClock中的实时时钟
var clock = document.getElementById('clock');
setInterval(function(){
clock.innerHTML = getCurrentTime();
}, 1);
function getCurrentTime() {
var currentDate = new Date();
var hours = currentDate.getHours() > 12 ? currentDate.getHours() - 12 : currentDate.getHours();
hours === 0 ? hours = 12 : hours = hours;
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds() < 10 ? '0' + currentDate.getSeconds() : currentDate.getSeconds();
var currentTime = hours + ':' + minutes + ':' + seconds;
return currentTime;
}
Try something like this.
试试这样的东西。
new Date()
will give you the date for today. After getting the date get the hour, minutes, seconds from today's date.
New date()将为您提供今天的日期。在得到日期之后,就可以得到今天日期的小时、分钟、秒。
setTimeout(startTime, 1000)
will help you to run the timer continuously.
SetTimeout(startTime,1000)将帮助您连续运行计时器。
<!DOCTYPE html>
<html>
<body onload="startTime()">
<h2>JavaScript Clock</h2>
<div id="txt"></div>
<script>
function startTime() {
const today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</body>
</html>
A simple clock would be somthing like
一只简单的钟大概是这样的
setInterval(() => {
let arr = Date().match(/\d{2}(?=:)|(?<=:)\d{2}/g).map(x => x = Number(x))
console.log(new Object({hours: arr[0], minutes: arr[1], seconds: arr[2]}))
},1000)
Its console logs out an array that is [h, m, s].
其控制台注销一个为[h,m,S]的数组。
var span = document.getElementById('clock');
function time() {
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes();
var h = d.getHours();
span.textContent =
("0" + h).substr(-2) + ":" + ("0" + m).substr(-2) + ":" + ("0" + s).substr(-2);
}
setInterval(time, 1000);
<span id="span"></span>
var span = document.getElementById('span');
function time() {
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes();
var h = d.getHours();
span.textContent =
("0" + h).substr(-2) + ":" + ("0" + m).substr(-2) + ":" + ("0" + s).substr(-2);
}
setInterval(time, 1000);
<span id="span"></span>
What do you mean by "new time of day"? But in order to replace new time, you can create a div contain the time, and every time you call time(), set that div.innerHTML = "", like below
什么叫“一天中的新时间”?但是为了替换新的时间,可以创建一个包含时间的div,每次调用time()时,设置该div.innerHTML =“",如下所示
HTML:
Html:
<div id="curr_time"></div>
JS:
JS:
var div = document.getElementById('curr_time');
function time() {
div.innerHTML = "";
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes();
var h = d.getHours();
div.innerHTML = h + ":" + m + ":" + s;
}
setInterval(time, 1000);
更多回答
Thank you! Didn't even think about that. Should have understood that. Anyways thank you!
谢谢!根本没想过这一点。我应该明白这一点。无论如何,谢谢你!
@williamganrot : glad to help you
@Williamganrot:很高兴为您提供帮助
It would be nice if you could explain in your answer what your code solves, instead of just posting some code...
如果您能在您的回答中解释您的代码解决了什么问题,而不是仅仅发布一些代码,那就太好了。
I have updated my answer with explanation, @Klaassiek ,thank you, it was my first time answering, would not repeat again.
我已经更新了我的回答并解释说,@Klaassiek,谢谢你,这是我第一次回答,不会再重复了。
The question states if you could give me some tips without saying the answer straight out
问题是,你是否可以给我一些小贴士,而不是直接回答
Above code will display clock in digital format
上面的代码将以数字格式显示时钟
Please try to give proper explanation of the answer.
请试着对答案作出适当的解释。
Doesn't the above code get the am/pm wrong between midnight and 1am? It should display 12:xx AM, but will show 12:xx PM.
上面的代码不是把午夜到凌晨1点之间的上午/下午弄错了吗?它应该显示12:xx AM,但将显示12:xx PM
This is the only correct answer on this page that accounts for drift. Thank you!
这是本页上唯一可以解释漂移的正确答案。谢谢!
Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
虽然这在理论上可能会回答这个问题,但最好是在这里包括答案的基本部分,并提供链接以供参考。
@MikeMcCaughan, I've updated my answer, hope this will help.
@MikeMcCaughan,我已经更新了我的答案,希望这能有所帮助。
我是一名优秀的程序员,十分优秀!