I've been working with several projects that I need to get the elapsed time between two dates. After mucking around with it - I've put it into a single FUNCTION that will return either:
Seconds (integer)
Minutes ('xx minutes')
Hours ('xx hours')
Days ('xx days')
String ('xx days yy hours zz minutes yy seconds')
This function takes 2 mandatory parameters - StartDate and EndDate, and you can optionally provide the 3rd parameter (format).
Calling syntax looks like this:
elements.result.text = globals.getElapsed(globals.gStartDate, globals.gEndDate, 'minutes');
I called my global method "getElapsed" - but you can call yours whatever you want - just be sure you change the name in the calling method. For example if you called your global method "myGreatGlobalMethod" then the calling script would be:
elements.result.text = globals.myGreatGlobalMethod(globals.gStartDate, globals.gEndDate, 'minutes');
I've posted the code below.
ENJOY!
Bob Cusick
==================================
- Code: Select all
//returns the elapsed time according to the format
//arg0 = start date
//arg1 = end date
//arg2 = format ('seconds', 'minutes', 'hours', 'days', 'string', '' -- blank returns full string)
//***********************************
//convert dates to milliseconds
var sTime = arguments[0];
var eTime = arguments[1];
var format = arguments[2].toLowerCase();
var output = '';
//***********************************
//do the math to get the values
var elapsedSeconds = Math.ceil((eTime - sTime)/1000);
var days = Math.floor(elapsedSeconds / 86400);
var hours = Math.floor((elapsedSeconds - (days*86400))/3600);
var minutes = Math.floor((elapsedSeconds - ((days * 86400) + (hours * 3600)))/60);
var seconds = Math.floor(elapsedSeconds - ((days * 86400) + (hours * 3600) + (minutes * 60)));
//***********************************
//format for the return values
if(days == 1) {
days = days + ' day';
} else {
days = days + ' days';
}
if(hours == 1) {
hours = hours + ' hour';
} else {
hours = hours + ' hours';
}
if(minutes == 1) {
minutes = minutes + ' minute';
} else {
minutes = minutes + ' minutes';
}
if(seconds == 1) {
seconds = seconds + ' second';
} else {
seconds = seconds + ' seconds';
}
//***********************************
//return based on what was requested
switch (format)
{
case 'seconds':
output = elapsedSeconds
break;
case 'minutes':
output = minutes
break;
case 'hours':
output = hours
break;
case 'days':
output = days
break;
default:
output = days + ' ' + hours + ' ' + minutes + ' ' + seconds
}
return output;