Mega Code Archive

 
Categories / Delphi / Examples
 

Working with hhmm 1.20+1.50=3.10 !!

Title: Working with hhmm: 1.20+1.50=3.10 ??!! Question: As one of the last bastions for people detesting modern times we still have the burden non-metric timecalculation. If you make applications where users have to enter a period of time we have a problem. We can't let them enter a metric figure like 1,5h for 1h.30m (what should they enter if it took 1h25m ?). So you let them enter 1.30 for 1h30m The problem arises, that you can't do anything with non-metric figures: 1.20 + 1.70 is NOT 2.90 but 3.10. I often make apps with this kind of problems, so I have 3 functions solving all problems for me. They don't cope with seconds, because the business I am in always rounds up to minutes. As seconds are exactly one single and equivalent step further then minutes it is simple to expand those functions to sumhhmmss, hhmmss2hhdd and hhdd2hhmmss resp. For simplicity I always interpretate fields as being hh.mm, but when a real lot of statistics/reporting is done on the figures I introduce a hidden field which holds the hhmm2hhdd value. In a report I show in the column the hhmm field but I calculate the total based on the hidden hhdd field and convert the total back with hhdd2hhmm as do statistical/financial calculations on the hhdd field. But only when a lof of that is involved, else I use the two conversionfunctions in the calculations. Answer: function sumhhmm(a, b: double): double; var h1: double; begin h1 := (INT(A) + INT(B)) * 60 + (frac(a) + frac(b)) * 100; result := int(h1 / 60) + (h1 - int(h1 / 60) * 60) / 100; end; function hhmm2hhdd(const hhmm: double): double; begin result := int(hhmm) + (frac(hhmm) / 0.6); end; function hhdd2hhmm(const hhdd: double): double; begin result := int(hhdd) + (frac(hhdd) * 0.6); end; Usage: // sumtime(1.20,1.50) = 3.10 // sumtime(1.20,- 0.50) = 0.30 // hhmm2hhdd(1.30) = 1.5 (1h.30m = 1.5h) // hhdd2hhmm(1.50) = 1.30 (1.5h = 1h30m)