Subtract timestamps

The result of subtracting one timestamp (TS2) from another (TS1) is a timestamp duration that specifies the number of years, months, days, hours, minutes, seconds, and microseconds between the two timestamps.

The data type of the result is DECIMAL(20,6). If TS1 is greater than or equal to TS2, TS2 is subtracted from TS1. If TS1 is less than TS2, however, TS1 is subtracted from TS2 and the sign of the result is made negative. The following procedural description clarifies the steps involved in the operation RESULT = TS1 - TS2:

If %MICSEC(TS2) <= %MICSEC(TS1) ;
    then %MICSEC(RESULT) = %MICSEC(TS1) - ;
    %MICSEC(TS2).

If %MICSEC(TS2) > %MICSEC(TS1) ;
    then %MICSEC(RESULT) = 1000000 + ;
    %MICSEC(TS1) - %MICSEC(TS2) ;
    and %SECOND(TS2) is incremented by 1.

The seconds and minutes part of the timestamps are subtracted as specified in the rules for subtracting times:

If %HOUR(TS2) <= %HOUR(TS1) ;
    then %HOUR(RESULT) = %HOUR(TS1) - %HOUR(TS2).

If %HOUR(TS2) > %HOUR(TS1) ;
    then %HOUR(RESULT) = 24 + %HOUR(TS1) - %HOUR(TS2) ;
    and %DAY(TS2) is incremented by 1.

The date part of the timestamp is subtracted as specified in the rules for subtracting dates.