Subject Re: [firebird-support] Never mind (time math)
Author Helen Borrie
At 04:50 PM 24/06/2005 -0500, you wrote:
>I got it (Delphi):
>
>
>
> iMinutesLate := MinutesBetween(qryLate.Fields[0].AsTime,
>qryLate.Fields[1].AsTime);

Hmm, but it's not happening in the database, is it?

Any date/time value can be subtracted by any other of the same type, to
give a result in days. So a DATE minus a DATE gives whole days as an
integer (strictly speaking, DECIMAL(9,0); a TIMESTAMP minus a TIMESTAMP
gives whole and part days as a DECIMAL(18,9); and TIME minus a TIME gives
seconds and part-seconds as DECIMAL(9,4).

Your "minutesBetween" is likely to give a wrong result if it's operating on
timestamp data and your calculation takes you across the boundary of a day.

In SQL, the expression (TimeStampB - TimeStampA) can be converted from days
to minutes using a calculation that gets you the granularity you want. The
main thing to watch out for is that you cast operands and results in a way
that doesn't risk a numerical overflow.

(TimestampB - TimestampA) * 1440 is OK from the POV of scale - you will get
a DECIMAL(18,9) result that you can cast to whole minutes like this:

cast ((TimestampB - TimestampA) * 1440) as INTEGER)

If you want to get fractions, e.g. tenths of minutes, just cast it to
decimal(9,1) instead:
cast ((TimestampB - TimestampA) * 1440) as decimal(9,1))

..and so on...

./heLen