2009-07-31 71 views
56

Tôi đang tìm một số mẫu đơn giản JavaScript để tính toán thời gian đã trôi qua. Kịch bản của tôi là, đối với một điểm thực thi cụ thể trong mã JavaScript, tôi muốn ghi lại thời gian bắt đầu. Và tại một điểm thực thi cụ thể khác trong mã JavaScript, tôi muốn ghi lại thời gian kết thúc.Tính toán thời gian đã trôi qua

Sau đó, tôi muốn tính thời gian đã trôi qua dưới dạng: số ngày, giờ, phút và giây trôi qua giữa thời gian kết thúc và thời gian bắt đầu, ví dụ: 0 Days, 2 Hours, 3 Minutes and 10 Seconds are elapsed.

Bất kỳ mẫu đơn giản nào có tham chiếu? :-)

Cảm ơn trước,

George

Trả lời

12

Hy vọng điều này sẽ giúp:

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

Câu trả lời hay. Làm thế nào để bạn có được kịch bản để bắt đầu khi tải trang? – rd42

+0

86501 là thời gian Cảm ơn Ramiz lần nữa. – rd42

2

Trước tiên, bạn luôn có thể lấy thời gian hiện tại bởi

var currentTime = new Date(); 

Sau đó, bạn có thể kiểm tra "ngày đẹp" này ví dụ ở http://www.zachleat.com/Lib/jquery/humane.js

Nếu điều đó không hiệu quả với bạn, chỉ cần google "javascript pretty date" và bạn sẽ tìm thấy hàng tá tập lệnh mẫu.

Chúc may mắn.

2
<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> 
+3

language = "Javascript"? Có thật không?;) – phairoh

+0

Cảm ơn nhận xét này. – adatapost

95

Hãy thử một cái gì đó như thế này (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 ; 
+1

Dòng cuối cùng phải là "var days = timeDiff;" .. timeDays không tồn tại. – ForOhFor

+0

Đây có phải là Math.floor() không? –

+0

I.e. Tôi đang làm điều này: function ms2Time (ms) { var secs = ms/1000; ms = Math.floor (ms% 1000); var minutes = secs/60; giây = Math.floor (giây% 60); var hours = minutes/60; phút = Math.floor (phút 60%); giờ = Math.floor (giờ% 24); giờ trở lại + ":" + phút + ":" + giây + "." + ms; } –

10

Cái gì đó như một đối tượng "Đồng hồ bấm giờ" nói đến cái tâm của tôi:

Cách sử dụng :

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

Thực hiện:

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

Tôi nghĩ rằng điều này chỉ là tuyệt vời! –

22

Hãy thử này ... chương trình java

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

ghi rằng nhập thời gian trôi qua trong vài giây cho mọi trường hợp đi xe đạp & định dạng đầu ra nên được như thế (giờ: phút: giây) cho EX: thời gian trôi qua trong 4150 giây = 1:09:10

5

Đây là những gì tôi đang sử dụng:

mili giây để một chuỗi thời gian định dạng khá:

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; 
} 
6
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]'); 
}; 

Benchmark

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

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

stopwatch.stop(); 

stopwatch.printElapsed(); 

Output

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() là không bắt buộc - chỉ cần vượt qua sai vào hàm constructor StopWatch.

+0

Liên kết 'performance.now()' đã chết. – reformed

Các vấn đề liên quan