【问题标题】:Compute elapsed time [duplicate]计算经过的时间[重复]
【发布时间】:2010-11-15 16:36:23
【问题描述】:

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

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

任何参考简单示例? :-)

提前致谢,

乔治

【问题讨论】:

    标签: javascript datetime


    【解决方案1】:

    尝试这样的事情 (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 ;
    

    【讨论】:

    • 最后一行应该是“var days = timeDiff;”.. timeDays 不存在。
    • 这不应该是 Math.floor() 吗?
    • 即我正在这样做:函数 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);返回小时+“:”+分钟+“:”+秒+“。” +毫秒; }
    • @Dr.YSG 这完全取决于你。我更喜欢四舍五入而不是去除小数部分。
    • 查看小提琴并将其改回全舍入,以查看舍入有什么问题,除了计算秒数。我不确定舍入 mods (%) 有什么目的,但我留下了你的代码。
    【解决方案2】:

    试试这个...

    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;
    }
    

    【讨论】:

      【解决方案3】:

      希望这会有所帮助:

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

      【讨论】:

      • 不错的答案。页面加载时如何启动脚本?
      • 86501 是时候了,再次感谢 Ramiz。
      【解决方案4】:

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

      用法:

      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;
        }   
      }
      

      【讨论】:

      • 我觉得这东西太棒了!
      【解决方案5】:
      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() 链接已失效。
      【解决方案6】:

      这是我正在使用的:

      毫秒到一个漂亮的格式化时间字符串:

      function ms2Time(ms) {
          var secs = ms / 1000;
          ms = Math.floor(ms % 1000);
          var minutes = secs / 60;
          secs = Math.floor(secs % 60);
          var hours = minutes / 60;
          minutes = Math.floor(minutes % 60);
          hours = Math.floor(hours % 24);
          return hours + ":" + minutes + ":" + secs + "." + ms;  
      }
      

      【讨论】:

        【解决方案7】:

        首先,你总是可以通过

        来获取当前时间
        var currentTime = new Date();
        

        然后你可以在http://www.zachleat.com/Lib/jquery/humane.js查看这个“漂亮的约会”示例

        如果这对您不起作用,只需 google “javascript pretty date”,您就会找到数十个示例脚本。

        祝你好运。

        【讨论】:

          【解决方案8】:
          <script type="text/javascript">
          <!-- Gracefully hide from old browsers
          
          // Javascript to compute elapsed time between "Start" and "Finish" button clicks
          function timestamp_class(this_current_time, this_start_time, this_end_time, this_time_difference) { 
                  this.this_current_time = this_current_time;
                  this.this_start_time = this_start_time;
                  this.this_end_time = this_end_time;
                  this.this_time_difference = this_time_difference;
                  this.GetCurrentTime = GetCurrentTime;
                  this.StartTiming = StartTiming;
                  this.EndTiming = EndTiming;
              }
          
              //Get current time from date timestamp
              function GetCurrentTime() {
              var my_current_timestamp;
                  my_current_timestamp = new Date();      //stamp current date & time
                  return my_current_timestamp.getTime();
                  }
          
              //Stamp current time as start time and reset display textbox
              function StartTiming() {
                  this.this_start_time = GetCurrentTime();    //stamp current time
                  document.TimeDisplayForm.TimeDisplayBox.value = 0;  //init textbox display to zero
                  }
          
              //Stamp current time as stop time, compute elapsed time difference and display in textbox
              function EndTiming() {
                  this.this_end_time = GetCurrentTime();      //stamp current time
                  this.this_time_difference = (this.this_end_time - this.this_start_time) / 1000; //compute elapsed time
                  document.TimeDisplayForm.TimeDisplayBox.value = this.this_time_difference;  //set elapsed time in display box
                  }
          
          var time_object = new timestamp_class(0, 0, 0, 0);  //create new time object and initialize it
          
          //-->
          </script>
          
              <form>
                  <input type="button" value="Start" onClick="time_object.StartTiming()"; name="StartButton">
              </form>
              <form>
                  <input type="button" value="Finish" onClick="time_object.EndTiming()"; name="EndButton">
              </form>
              <form name="TimeDisplayForm">
              Elapsed time:
                <input type="text" name="TimeDisplayBox" size="6">
              seconds
              </form>
          

          【讨论】:

          • 语言="Javascript"?真的吗? ;)
          • 感谢您的评论。
          【解决方案9】:

          编写 java 程序,输入任何循环事件的经过时间(以秒为单位),输出格式应类似于(小时:分钟:秒)EX:4150 秒内经过的时间= 1:09:10

          【讨论】:

            猜你喜欢
            • 2015-11-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-04-25
            • 2020-12-01
            • 1970-01-01
            相关资源
            最近更新 更多