Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

html - JavaScript code to run the Clock (date and time) four times faster

I am in need of virtual time (4 x current date and time). I have managed to display the running clock with the current date and time, but I am unable to the time four times faster than current time.

For example, if the current date is 01-01-2012 00:00:00, the virtual time should be 01-01-2012 00:00:04

Not only the seconds alone should get multiplied; the corresponding minutes, hours, date, month and year also should get multiplied when seconds crosses 59 virtual seconds. That is, the clock should run live with incremental of four seconds for every second with my date format.

Please see my page: http://www.chemfluence.org.in/sample.html

It's now running with the current time. I want to run this four times faster.

Please see my code below.

<!DOCTYPE html>
<html>
    <head>
        <script>
            function startTime()
            {
                var today = new Date();
                var h = today.getHours();
                var m = today.getMinutes();
                var s = today.getSeconds();
                // Add a zero in front of numbers<10
                m = checkTime(m);
                s = checkTime(s);
                document.getElementById('txt').innerHTML =
                    today.getDate() +
                    "-" +
                    (today.getMonth()+1)+"-" +
                    today.getFullYear() +
                    " "+h+":"+m+":"+s;
                t = setTimeout(function(){startTime()},500);
            }

            function checkTime(i)
            {
                if (i<10)
                {
                    i = "0" + i;
                }
                return i;
            }
        </script>
    </head>

    <body onload="startTime()">
        <div id="txt"></div>
    </body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a simple formula to determine the virtual time for every given time, knowing the two timestamps and the factor:

var virtualOrigin = Date.parse("2012-01-01T00:00:04"),
    realOrigin = Date.parse("2012-01-01T00:00:00"),
    factor = 4;

function getVirtual(time) {
    return new Date( virtualOrigin + (time - realOrigin) * factor );
}

// usage:
var now = new Date(),
    toDisplay = getVirtual(now);

Demo at jsfiddle.net


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...