views:

1755

answers:

6

Hello everyone,

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 minute and 10 seconds are elapsed. Any reference simple samples? :-)

thanks in advance, George

+1  A: 

First, you can always grab the current time by

var currentTime = new Date();

Then you could check out this "pretty date" example at http://www.zachleat.com/Lib/jquery/humane.js

If that doesn't work for you, just google "javascript pretty date" and you'll find dozens of example scripts.

Good luck.

Derek Gathright
+1  A: 
<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>
adatapost
language="Javascript"? Really? ;)
Phairoh
Thanks for this comment.
adatapost
+4  A: 

Try something like this

// 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 miliseconds
var timeDiff /= 1000;

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

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

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

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

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

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

// the rest of timeDiff is number of days
var days = timeDays;
RaYell
+1  A: 

Hi,

Hope this will help:

<!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>
Ramiz Uddin
+1  A: 

Something like a "Stopwatch" object comes to my mind:

Usage:

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

Implementation:

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;
  }   
}
CMS
+1  A: 

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