Calculate Elapsed Time

I'm looking for the cleanest way to calculate the time elapsed between two times in KSH. In minutes or in hours and minutes if it has been longer than 59 minutes.

Here are some random examples:

Example result: 25 Minutes
or
Example result: 1 Hour and 25 Minutes

Example time format:
"23:45:33 EDT 2004" and "00:25:06 EDT 2004"

If anyone has a solution or idea, I would be very grateful. These types of problems just seem to throw the brakes on my brain right from the start. Thanks for any help :slight_smile:

-Sys

shell% man time

Here is a tip:

Convert your times to seconds and do your calculations in seconds. If you want to display, convert back from seconds.

Enjoy!

Convert times to minutes; subtract start time from end time; if negative then started before mignight; print result....

#!usr/bin/ksh

start="23:45:33 EDT 2004"
end="00:25:06 EDT 2004"

((start_mins = $(expr substr "$start" 1 2)*60 + $(expr substr "$start" 4 2)))
((end_mins = $(expr substr "$end" 1 2)*60 + $(expr substr "$end" 4 2)))
((elapsed_mins = end_mins - start_mins))

if [[ "$elapsed_mins" -lt 0 ]]
then
   ((elapsed_mins += 1440))
fi

if [[ "$elapsed_mins" -gt 59 ]]
then
   print $((elapsed_mins / 60)) hours and $((elapsed_mins % 60)) minutes
else
   print $elapsed_mins minutes
fi

ksh has a built-in SECONDS variable. Just do:
orig=$SECONDS
some_command
((elasped=SECONDS-orig))
echo $elasped

Thank you Ygor, that does exactly what I was looking for. Some day I too will be able to make these insane things up on my own with a little help from examples like yours. :slight_smile:

-Sys