Thursday, July 25, 2013

How to calculate the elapsed time between two Date-Time fields




I have found several functions, scripts and blogs providing different methods to calculate the elapsed time between two date-time fields. However, most of them are hard to understand or involve a higher coding of deluge scripting to obtain the desired result.

Below you will find a solution in 3 lines of code if the Dates belong to the same day

Hr=(input.End_Time.getHour()  -  input.Start_Time.getHour());
Min=(input.End_Time.getMinutes()  /  60  -  input.Start_Time.getMinutes()  /  60);
Elapsed=(Hr  +  Min);

Or 7 lines of code If the Dates vary in Days ...

if(input.Start_Time.getDayOfWeek()  ==  input.End_Time.getDayOfWeek())
{
Hr=(input.End_Time.getHour()  -  input.Start_Time.getHour());
Min=(input.End_Time.getMinutes()  /  60  -  input.Start_Time.getMinutes()  /  60);
Elapsed=(Hr  +  Min);
}
else if(input.Start_Time.getDayOfWeek()  <  input.End_Time.getDayOfWeek())
{
Hr=(input.End_Time.getHour()  -  input.Start_Time.getHour());
Min=(input.End_Time.getMinutes()  /  60  -  input.Start_Time.getMinutes()  /  60);
Day=((input.End_Time.getDayOfYear()  -  input.Start_Time.getDayOfYear())  *  24);
Elapsed=(Day  +  Hr  +  Min);
}

In the following link you will be able to test the script on a live and free application. Elapsed Time

You may locate the following code in the following places: On user input, On Add On Success, or On Edit On Success

Hope it helps....enjoy.
f76bbaee41a7ad6eb60d2a96b6829bce83014907fa936980c3

No comments:

Post a Comment