Hi All,

Recently had a request for some sample code to: calculate the duration time between two date/times, for example, time between: March 3, 2013 11:50 and March 4, 2013 10:45.

That didn’t sound too hard, but ended up taking me longer than I thought. I wonder if others might have a more elegant solution than mine.

The method I used involved:

- calculating each date/time in terms of seconds since 0,
- subtracting one from the other,
- then building the result in human-readable form (leveraging previously shared “ConvertInteger32ToTimestampString” subroutine).

```
// Get date/time in terms of seconds since year 0.
// Add up all the seconds since the start of year 0
// (365.25 * 24) * (60 * 60);
nnWholeYearsInSeconds = (nYear - 1) * (8766i64) * 3600i64;
// now we have the whole years so far in seconds since year 0;
// Now the number of days that have passed in the current year. For that we need to know the # of days
// per month, which breaks down like this:
ntDaysPerMonth[1] = 31;
ntDaysPerMonth[2] = 28;
ntDaysPerMonth[3] = 31;
ntDaysPerMonth[4] = 30;
ntDaysPerMonth[5] = 31;
ntDaysPerMonth[6] = 30;
ntDaysPerMonth[7] = 31;
ntDaysPerMonth[8] = 31;
ntDaysPerMonth[9] = 30;
ntDaysPerMonth[10] = 31;
ntDaysPerMonth[11] = 30;
ntDaysPerMonth[12] = 31;
// Figure out how many days have gone by so far this year, not counting this month/day
nDaysSinceYearStart = 0;
if (nMonth > 1) then
for nMonthIndex = 1 to (nMonth - 1) step 1
nDaysSinceYearStart = nDaysSinceYearStart + ntDaysPerMonth[nMonth];
next
if (nMonth > 2) then // we need to figure out if this is a leap year, and if so, add an extra day for the 29th
if ((nYear % 4) == 0) then // the year is evenly divisible by 4, therefore, a leap year
nDaysSinceYearStart = nDaysSinceYearStart + 1;
endif
endif
endif
// Now add the number of days (except for the current one, which is not done yet, so shouldn't be counted
// as a full day)
nDaysSinceYearStart = nDaysSinceYearStart + (nDay - 1);
nnWholeDaysInSeconds = (nDaysSinceYearStart * 86400i64); //24 * 60 * 60 how much of this year passed, in whole days, units of seconds
// Figure out how many seconds have passed since the beginning of the day in question
nSecondsSinceDayStart = (nHour * 60 * 60) + (nMinute * 60) + nSecond;
nnTotalSeconds = nnWholeYearsInSeconds + nnWholeDaysInSeconds + nSecondsSinceDayStart;
```

Comments? Questions? Other suggestions?

Thanks,

-OptoMary

ElapsedTimeCalc.v1.0.zip (7.8 KB)