Skip to content

ABAP Keyword Documentation →  ABAP − Reference →  Processing Internal Data →  Date and Time Processing →  Date Fields and Time Fields →  Access to Date Fields and Time Fields 

Evaluating Date Fields and Time Fields

This example demonstrates calculations with date and time fields.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    DATA: ultimo TYPE d,
          t1 TYPE t VALUE '000000',
          t2 TYPE t,
          diff TYPE i,
          seconds TYPE i,
          hours TYPE i.

    "date calculation

    ultimo      = sy-datlo.
    ultimo+6(2) = '01'.
    ultimo     -= 1.
    cl_demo_output=>write(
      |Last day of last month: { ultimo }| ).

    "time calculation

    t2 = sy-timlo.
    diff = t2 - t1.
    seconds = diff MOD 86400.
    hours = seconds / 3600.
    cl_demo_output=>display(
      |Number of hours since midnight: { hours }| ).

Description

In the first part of the main method, the last day of the previous month is assigned to ultimo. First, ultimo is filled with the current date. Then the date is changed to the first day of the current month using an offset. Finally, 1 is subtracted from ultimo, so that the content of the field is changed to the last day of the previous month. Before the subtraction takes place, the system converts ultimo into the number of days since 01.01.0001 and converts the result back into a date.

In the second part, the number of hours between midnight and the current time are calculated. First, the difference between the time fields is calculated. The difference is then converted into the total number of seconds using the MOD operation. A positive difference remains unchanged. This step is only required for negative differences. Finally, the number of hours is calculated by dividing the number of seconds by 3600.