Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute elapsed time [duplicate]

I am looking for some JavaScript simple samples to compute elapsed time. My scenario is, for a specific point of execution in JavaScript code, I want to record a start time. And at another specific point of execution in JavaScript code, I want to record an end time.

Then, I want to calculate the elapsed time in the form of: how many Days, Hours, Minutes and Seconds are elapsed between end time and start time, for example: 0 Days, 2 Hours, 3 Minutes and 10 Seconds are elapsed.

Any reference simple samples? :-)

Thanks in advance,

George

like image 299
George2 Avatar asked Jul 31 '09 04:07

George2


People also ask

How do you calculate elapsed time?

In simple words, we can say that the amount of time that has passed between the beginning and the end of an event is called the elapsed time. We can determine this time by subtracting the end time and the start time. The formula to calculate the elapsed time is simply to subtract the hours and minutes separately.

How do you calculate elapsed time in Javascript?

getTime() - startTime. getTime(); Note: the getTime() built-in date function returns the elapsed time between Jan 1st, 1970 00:00:00 UTC and the given date.

What is actual elapsed time example?

A schedule defined from 9am to 5pm is 8 hours long. If a task SLA starts at 12am, and the current time is 12pm, then the actual elapsed time is 12 hours, but the business elapsed time is 5 hours, and the business elapsed time will only restart at 9am on the following day.


2 Answers

Try something like this (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 ; 
like image 157
RaYell Avatar answered Oct 22 '22 05:10

RaYell


Try this...

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; } 
like image 40
rp. Avatar answered Oct 22 '22 07:10

rp.