Tuesday, August 21, 2012

Converting a minutes to hours, minutes,seconds format

So you have finally reached the point when 145.8 minutes simply will not work for your boss... But how to convert to Hours, Minutes, Seconds format in Crystal Reports?

Everyone knows how to convert minutes to days and seconds--but telling your program is an different matter entirely. The secret is the Mod operator. When we convert from minutes to hours minutes and seconds, the first thing we do is divide our total number of minutes by 60 and shed the remainder as minutes. This is done via the Mod operator. It returns the remainder after division. So 144/60 = hours and 144 Mod 60=minutes and seconds is (144 mod 60)/60... In Crystal Reports, we have to multiply the number of seconds time 100 to avoid unsightly decimal points.

The code is fairly straightforward once you get the hang of it:

Pseudo-Code:
If you code is large enough to contain hours
then show the number without decimal places as hours
show the number of minutes without decimals
show the seconds
Otherwise, if your total does not contain hours
then the total number of seconds is found after the decimal place in the minutes column

Code:
if({your_total}/60>1) then                          
  cstr(({your_total}/60,0,'')+' Hours, '         
  + cstr({your_total} mod 60,0,'')+' Minutes' 
  +cstr(({your_total}mod 60,0,'')/60*100,0,'') + 'Seconds'   

else                                                      
  cstr({your_total}mod 60,0,'')+'Minutes '+cstr((({your_total}mod 60)-{your_total})*100,0,'')+'Seconds'

And that is the basic idea. You will need to make modifications if you need to break down by day/month/year... but this should get you started.