Date and Time Calculations

Date and time fields have character types, not numeric ones. However, you can still use date and time fields in numeric operations. To allow you to do so, the system performs automatic type conversions. You may also find it useful to use offset and length specifications when using date and time fields in calculations.

Example of a date calculation:

DATA: ULTIMO TYPE D.

ULTIMO = SY-DATUM.
ULTIMO+6(2) = '01'.          " = first day of this month
ULTIMO = ULTIMO - 1. " = last day of last month

Here, the last day of the previous month is assigned to the date field ULTIMO.

1. ULTIMO is filled with the present date.

2. Using an offset specification, the day is changed to the first day of the current month.

3. 1 is subtracted from ULTIMO. Its contents are changed to the last day of the previous month. Before performing the subtraction, the system converts ULTIMO to the number of days since 01.01.0001 and converts the result back to a date.

Example of a time calculation:

DATA: DIFF TYPE I,
SECONDS TYPE I,
HOURS TYPE I.

DATA: T1 TYPE T VALUE '200000',
T2 TYPE T VALUE '020000'.

DIFF = T2 - T1.
SECONDS = DIFF MOD 86400.
HOURS = SECONDS / 3600.

The number of hours between 02:00:00 and 20:00:00 is calculated.

1. First, the difference between the time fields is calculated. This is -64800, since T1 and T2 are converted internally into 72000 and 7200 respectively.

2. Second, with the operation MOD, this negative difference is converted to the total number of seconds. A positive difference would be unaffected by this calculation.

3. Third, the number of hours is calculated by dividing the number of seconds by 3600.

The last three lines can be replaced by the following line

HOURS = ( ( T2 - T1 ) MOD 86400 ) / 3600.

Inverted Dates

In some cases (for example, when sorting dates in descending order), it is useful to convert a date from format D to an inverted date by using the keyword CONVERT.

CONVERT DATE <d1> INTO INVERTED-DATE <d2>.

Afterwards, you can convert the inverted data back into a normal date using the statement

CONVERT INVERTED-DATE <d1> INTO DATE <d2>.

These statements convert the field <d1> from the formats DATE or INVERTED-DATE to the formats INVERTED-DATE or DATE and assign it to the field <d2>.

For the conversion, ABAP forms the nine's complement.

DATA: ODATE TYPE D VALUE '19955011',
IDATE LIKE ODATE.

DATA FIELD(8).

FIELD = ODATE.   WRITE / FIELD.

CONVERT DATE ODATE INTO INVERTED-DATE IDATE.

FIELD = IDATE.   WRITE / FIELD.

CONVERT INVERTED-DATE IDATE INTO DATE ODATE.

FIELD = ODATE.   WRITE / FIELD.

Output:

80049488

19955011

19955011