使用 javascript 在 div 中使用现有时间制作实时时钟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10931197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:30:55  来源:igfitidea点击:

make a live clock with existing time in div with javascript

javascript

提问by Adam Ramadhan

ok lets say we have a website that need a realtime time;

好吧,假设我们有一个需要实时的网站;

example :

例子 :

<div id="updatetime">21:12:52</div>

<div id="updatetime">21:12:52</div>

each seconds update hours:m:second.

每秒更新小时:米:秒。

what i have in minds using the interval functionto do long pool and add the sec +1 if to 60 then add + 1 to m and same as hours. but is there a function already solving this problem?

我的想法是使用interval functionto do long pool 并将 sec +1 if 添加到 60 然后将 +1 添加到 m 和小时数相同。但是有没有一个功能已经解决了这个问题?

how do you make this 21:12:52a moving real clock with javascript that updates each seconds?

您如何21:12:52使用每秒更新一次的 javascript使其成为一个移动的真实时钟?

i have search google, stackoverflow, many of them tells us how to make the current real time datetime from javascript. but none from an existing time. if there is please do insert the link.

我搜索过 google、stackoverflow,其中很多都告诉我们如何从 javascript 生成当前的实时日期时间。但没有从现有的时间。如果有请插入链接。

回答by Steve

It can be as easy as this:

它可以像这样简单:

setInterval(function(){
    document.getElementById("updatetime").innerHTML = (new Date()).toLocaleTimeString();
}, 1000);

Or use the other Date methodsto fine-tune your output.

或者使用其他 Date 方法来微调您的输出。

Update

更新

I only now realized that OP was asking not about incrementing an element with the currenttime but with a predeterminedtime.

我现在才意识到 OP 要求的不是用当前时间而是用预定时间来增加元素。

That's less trivial, but here is a solution that should fit the original question:

这不是那么简单,但这里有一个适合原始问题的解决方案:

function increment_time_element(element, delay) {
    var interval, last,
        time_pattern = /(\d+):(\d+):(\d+)/,
        start = element.innerHTML.match(time_pattern),
        then = new Date;

    then.setHours  (parseInt(start[1], 10) || 0);
    then.setMinutes(parseInt(start[2], 10) || 0);
    then.setSeconds(parseInt(start[3], 10) || 0);

    function now() {
        return Date.now ? Date.now() : (new Date).getTime();
    }

    last = now();

    interval = setInterval(function () {
        var current = now();
        // correct for any interval drift by using actual difference
        then.setTime(then.getTime() + current - last)
        last = current;
        element.innerHTML = then.toString().match(time_pattern)[0];
    }, delay || 1000);

    return {cancel: function() { clearInterval(interval) }};
}

// Usage:
var incrementing_time =
    increment_time_element(document.getElementById("updatetime"));

// Then, if you want to cancel:
incrementing_time.cancel();

回答by ZER0

If you don't need a very high fidelity, you can use this way:

如果你不需要非常高的保真度,你可以这样使用:

?var container  = document.getElementById("updatetime").firstChild;
var values = container.nodeValue.split(":");

// Because there is only a datetime specified, I assume is the current date
var now = new Date();
var time = new Date(now.getFullYear(), now.getMonth(), now.getDate(),
                    values[0], values[1], values?[2]).getTime();

setInterval(function() {
    time += 1000;
    var date = new Date(time);
    var values = [date.getHours(), date.getMinutes(), date.getSeconds()];

    for (var i = 0; i < 3; i++)
        if (values[i] < 10)
            values[i] = "0" + values[i];

    container.nodeValue = values.join(":");
}, 1000);

If you want to be more in sync with the current computer clock, then I suggest to you to use setTimeoutand adjust the delayargument with the proper elapsed time.

如果您想与当前的计算机时钟更加同步,那么我建议您使用setTimeout并调整delay适当的经过时间的参数。

Update: due the comments, it seems the elements to update are not only one and multiple, and the code is using jQuery. Here an approach that works for multiple elements using classto identify them:

更新:由于评论,似乎要更新的元素不仅是一个和多个,而且代码使用的是 jQuery。这是一种适用于多个元素的方法class来识别它们:

var containers  = $(".updatetime");
var times = [];
var now = new Date();

containers.each(function(index, node) {
    var values = $(node).text().split(":");

    times[index] = new Date(
        now.getFullYear(), now.getMonth(), now.getDate(),
        values[0], values[1], values[2]).getTime();
});

setInterval(function() {
    containers.each(function(index, node) {
        times[index] += 1000;

        var date = new Date(times[index]);
        var values = [date.getHours(), date.getMinutes(), date.getSeconds()];

        for (var i = 0; i < 3; i++)
            if (values[i] < 10)
                values[i] = "0" + values[i];

        $(node).text(values.join(":"));
    });

}, 1000);

回答by Marc

If your after a realtime clock that ticks along, take a look at the code I used when I created a "flip clock". I split each digit into a seperate individual digit to use for graphic placement within the clock, but if you strip it down you will have just text that updates.

如果您使用的是实时时钟,请查看我创建“翻转时钟”时使用的代码。我将每个数字拆分成一个单独的数字,用于时钟内的图形放置,但如果将其剥离,则只会有更新的文本。

Javascript Flip Clock

Javascript翻转时钟

回答by Mahendra Kulkarni

using HTML canvas

使用 HTML canvas

code:

代码:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90
setInterval(drawClock, 1000);

function drawClock() {
  drawFace(ctx, radius);
  drawNumbers(ctx, radius);
  drawTime(ctx, radius);
}

function drawFace(ctx, radius) {
  var grad;
  ctx.beginPath();
  ctx.arc(0, 0, radius, 0, 2 * Math.PI);
  ctx.fillStyle = 'white';
  ctx.fill();
  grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05);
  grad.addColorStop(0, '#333');
  grad.addColorStop(0.5, 'white');
  grad.addColorStop(1, '#333');
  ctx.strokeStyle = grad;
  ctx.lineWidth = radius * 0.1;
  ctx.stroke();
  ctx.beginPath();
  ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);
  ctx.fillStyle = '#333';
  ctx.fill();
}

function drawNumbers(ctx, radius) {
  var ang;
  var num;
  ctx.font = radius * 0.15 + "px arial";
  ctx.textBaseline = "middle";
  ctx.textAlign = "center";
  for (num = 1; num < 13; num++) {
    ang = num * Math.PI / 6;
    ctx.rotate(ang);
    ctx.translate(0, -radius * 0.85);
    ctx.rotate(-ang);
    ctx.fillText(num.toString(), 0, 0);
    ctx.rotate(ang);
    ctx.translate(0, radius * 0.85);
    ctx.rotate(-ang);
  }
}

function drawTime(ctx, radius) {
  var now = new Date();
  var hour = now.getHours();
  var minute = now.getMinutes();
  var second = now.getSeconds();
  //hour
  hour = hour % 12;
  hour = (hour * Math.PI / 6) +
    (minute * Math.PI / (6 * 60)) +
    (second * Math.PI / (360 * 60));
  drawHand(ctx, hour, radius * 0.5, radius * 0.07);
  //minute
  minute = (minute * Math.PI / 30) + (second * Math.PI / (30 * 60));
  drawHand(ctx, minute, radius * 0.8, radius * 0.07);
  // second
  second = (second * Math.PI / 30);
  drawHand(ctx, second, radius * 0.9, radius * 0.02);
}

function drawHand(ctx, pos, length, width) {
  ctx.beginPath();
  ctx.lineWidth = width;
  ctx.lineCap = "round";
  ctx.moveTo(0, 0);
  ctx.rotate(pos);
  ctx.lineTo(0, -length);
  ctx.stroke();
  ctx.rotate(-pos);
}
<canvas id="canvas" width="400" height="400" style="background-color:#333">
</canvas>

回答by Sandip Moradiya

you can do it with below code

你可以用下面的代码来做

<!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>