计算经过时间

IT技术 javascript datetime
2021-02-26 01:26:55

我正在寻找一些 JavaScript 简单示例来计算经过的时间。我的场景是,对于 JavaScript 代码中的特定执行点,我想记录一个开始时间。在 JavaScript 代码的另一个特定执行点,我想记录结束时间。

然后,我想以以下形式计算经过的时间:结束时间和开始时间之间经过了多少天,小时,分钟和秒,例如:0 Days, 2 Hours, 3 Minutes and 10 Seconds are elapsed

任何参考简单的样本?:-)

提前致谢,

乔治

6个回答

尝试这样的事情(FIDDLE

// record start time
var startTime = new Date();

...

// later record end time
var endTime = new Date();

// time difference in ms
var timeDiff = endTime - startTime;

// strip the ms
timeDiff /= 1000;

// get seconds (Original had 'round' which incorrectly counts 0:28, 0:29, 1:30 ... 1:59, 1:0)
var seconds = Math.round(timeDiff % 60);

// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);

// get minutes
var minutes = Math.round(timeDiff % 60);

// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);

// get hours
var hours = Math.round(timeDiff % 24);

// remove hours from the date
timeDiff = Math.floor(timeDiff / 24);

// the rest of timeDiff is number of days
var days = timeDiff ;
@Dr.YSG 这真的取决于你。我更喜欢四舍五入值而不是剥离分数部分。
2021-04-24 01:26:55
最后一行应该是“var days = timeDiff;”... timeDays 不存在。
2021-04-29 01:26:55
查看小提琴并将其改回所有四舍五入以查看除计算秒数之外的四舍五入有什么问题。我不确定四舍五入 mods (%) 是否有任何目的,但我留下了您的代码。
2021-05-01 01:26:55
即我这样做:function ms2Time(ms) { var secs = ms / 1000; ms = Math.floor(ms % 1000); var 分钟 = 秒 / 60; secs = Math.floor(secs % 60); var 小时 = 分钟 / 60; 分钟 = Math.floor(分钟 % 60); 小时 = Math.floor(小时 % 24); 返回小时 + ":" + 分钟 + ":" + secs + "." + 毫秒;}
2021-05-03 01:26:55
这不应该是 Math.floor() 吗?
2021-05-05 01:26:55

试试这个...

function Test()
{
    var s1 = new StopWatch();

    s1.Start();        

    // Do something.

    s1.Stop();

    alert( s1.ElapsedMilliseconds );
} 

// Create a stopwatch "class." 
StopWatch = function()
{
    this.StartMilliseconds = 0;
    this.ElapsedMilliseconds = 0;
}  

StopWatch.prototype.Start = function()
{
    this.StartMilliseconds = new Date().getTime();
}

StopWatch.prototype.Stop = function()
{
    this.ElapsedMilliseconds = new Date().getTime() - this.StartMilliseconds;
}

希望这会有所帮助:

<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
    <head>
        <title>compute elapsed time in JavaScript</title>

        <script type="text/javascript">

            function display_c (start) {
                window.start = parseFloat(start);
                var end = 0 // change this to stop the counter at a higher value
                var refresh = 1000; // Refresh rate in milli seconds
                if( window.start >= end ) {
                    mytime = setTimeout( 'display_ct()',refresh )
                } else {
                    alert("Time Over ");
                }
            }

            function display_ct () {
                // Calculate the number of days left
                var days = Math.floor(window.start / 86400);
                // After deducting the days calculate the number of hours left
                var hours = Math.floor((window.start - (days * 86400 ))/3600)
                // After days and hours , how many minutes are left
                var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60)
                // Finally how many seconds left after removing days, hours and minutes.
                var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)))

                var x = window.start + "(" + days + " Days " + hours + " Hours " + minutes + " Minutes and " + secs + " Secondes " + ")";

                document.getElementById('ct').innerHTML = x;
                window.start = window.start - 1;

                tt = display_c(window.start);
            }

            function stop() {
                clearTimeout(mytime);
            }

        </script>

    </head>

    <body>

        <input type="button" value="Start Timer" onclick="display_c(86501);"/> | <input type="button" value="End Timer" onclick="stop();"/>
        <span id='ct' style="background-color: #FFFF00"></span>

    </body>
</html>
很好的答案。如何在页面加载时启动脚本?
2021-05-01 01:26:55
<body onload="display_c(86501);"> 86501 是时候了,再次感谢 Ramiz。
2021-05-07 01:26:55

我想到了类似“秒表”对象的东西:

用法:

var st = new Stopwatch();
st.start(); //Start the stopwatch
// As a test, I use the setTimeout function to delay st.stop();
setTimeout(function (){
            st.stop(); // Stop it 5 seconds later...
            alert(st.getSeconds());
            }, 5000);

执行:

function Stopwatch(){
  var startTime, endTime, instance = this;

  this.start = function (){
    startTime = new Date();
  };

  this.stop = function (){
    endTime = new Date();
  }

  this.clear = function (){
    startTime = null;
    endTime = null;
  }

  this.getSeconds = function(){
    if (!endTime){
    return 0;
    }
    return Math.round((endTime.getTime() - startTime.getTime()) / 1000);
  }

  this.getMinutes = function(){
    return instance.getSeconds() / 60;
  }      
  this.getHours = function(){
    return instance.getSeconds() / 60 / 60;
  }    
  this.getDays = function(){
    return instance.getHours() / 24;
  }   
}
我觉得这东西太棒了!
2021-05-11 01:26:55
var StopWatch = function (performance) {
    this.startTime = 0;
    this.stopTime = 0;
    this.running = false;
    this.performance = performance === false ? false : !!window.performance;
};

StopWatch.prototype.currentTime = function () {
    return this.performance ? window.performance.now() : new Date().getTime();
};

StopWatch.prototype.start = function () {
    this.startTime = this.currentTime();
    this.running = true;
};

StopWatch.prototype.stop = function () {
    this.stopTime = this.currentTime();
    this.running = false;
};

StopWatch.prototype.getElapsedMilliseconds = function () {
    if (this.running) {
        this.stopTime = this.currentTime();
    }

    return this.stopTime - this.startTime;
};

StopWatch.prototype.getElapsedSeconds = function () {
    return this.getElapsedMilliseconds() / 1000;
};

StopWatch.prototype.printElapsed = function (name) {
    var currentName = name || 'Elapsed:';

    console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};

基准

var stopwatch = new StopWatch();
stopwatch.start();

for (var index = 0; index < 100; index++) {
    stopwatch.printElapsed('Instance[' + index + ']');
}

stopwatch.stop();

stopwatch.printElapsed();

输出

Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]

performance.now()是可选的 - 只需将 false 传递给 StopWatch 构造函数。

performance.now()链接已经死了。
2021-05-01 01:26:55