Calculating with Dates, Times, and Timestamps

Objective

After completing this lesson, you will be able to Calculate with dates, times, and timestamps.

Calculations with Dates, Times, and Timestamps

The built-in ABAP types D and T allow you to represent a day and a time respectively. Dates always have the format YYYYMMDD, regardless of the output format of the user. Times always have the format HHMMSS in 24-hour clock notation, regardless of the output format of the user. Times are accurate to 1 second.

System Information for Time and Date

The class cl_abap_context_info provides methods that you can use to find out current time and date information.

Watch the following video to learn more.

Date and Time Calculations

In ABAP, you can perform direct date calculations such as finding the difference between two dates or adding and subtracting a number of days from a given date. To perform the calculation, ABAP converts the dates into an integer (the number of days since 01.01.0001) and adds or subtracts the relevant values. When performing time calculations, ABAP converts the time into the number of seconds since midnight.

Using Offset and Length with Date Fields

ABAP stores dates in the format YYYYMMDD. You can access individual components of the date using offset and length. To access the month, for example, you need the fifth and sixth characters of the date field. You can do this by specifying var_date+4(2), which tells the system to go four characters into the date, then take the next two characters. The access to year, month, and day is then as follows:

  • Year: var_date(4)
  • Month: var_date+4(2)
  • Day: var_date +6(2)

Using Timestamp Fields

As well as the type D, ABAP has a built-in data type utclong, which represents a timestamp according to ISO-8601. This data type has an accuracy of 100 nanoseconds and follows the format YYYY-MM-DDTHH:MM:SS.sssssssZ, where T is the delimiter between date and time, and Z denotes the time zone Zulu, which stands for UTC.

Watch the following video to learn more about how to use the Timestamp fields.

Try It Out - Calculations with Times, Dates, and Timestamps

  1. Create a new class that implements the interface IF_OO_ADT_CLASSRUN.
  2. Copy the following code into the editor between the METHOD if_oo_adt_classrun~main. and ENDMETHOD. statements:
    Code Snippet
    Copy code
    Switch to dark mode
    123456789101112131415161718192021222324252627
    DATA timestamp1 TYPE utclong. DATA timestamp2 TYPE utclong. DATA difference TYPE decfloat34. DATA date_user TYPE d. DATA time_user TYPE t. timestamp1 = utclong_current( ). out->write( |Current UTC time { timestamp1 }| ). timestamp2 = utclong_add( val = timestamp1 days = 7 ). out->write( |Added 7 days to current UTC time { timestamp2 }| ). difference = utclong_diff( high = timestamp2 low = timestamp1 ). out->write( |Difference between timestamps in seconds: { difference }| ). out->write( |Difference between timestamps in days: { difference / 3600 / 24 }| ). CONVERT UTCLONG utclong_current( ) INTO DATE date_user TIME time_user TIME ZONE cl_abap_context_info=>get_user_time_zone( ). out->write( |UTC timestamp split into date (type D) and time (type T )| ). out->write( |according to the user's time zone (cl_abap_context_info=>get_user_time_zone( ) ).| ). out->write( |{ date_user date = user }, { time_user time = user }| ).
  3. Activate the class by pressing Ctrl + F3.
  4. Play around with the code to familiarize yourself with the topic.

Perform Calculations with Timestamps

In this exercise, you add the flight duration to the console output of your ABAP class. You calculate the flight duration based on the departure time and the arrival time, taking into account the different timezones of departure airport and destination airport.

Template:

  • /LRN/CL_S4D401_TCS_TYPE_CONV (Global Class)

Solution:

  • /LRN/CL_S4D401_TCS_TIMESTAMP (Global Class)

Task 1: Copy Template (Optional)

Copy the template class. If you finished the previous exercise, you can skip this task and continue editing your class ZCL_##_SOLUTION.

Steps

  1. Copy class /LRN/CL_S4D401_TCS_TYPE_CONV to a class in your own package (suggested name: ZCL_##_SOLUTION, where ## stands for your group number).

    1. In the Project Explorer view, right-click class /LRN/CL_S4D401_TCS_TYPE_CONV to open the context menu.

    2. From the context menu, choose Duplicate ....

    3. Enter the name of your package in the Package field. In the Name field, enter the name ZCL_##_SOLUTION, where ## stands for your group number.

    4. Adjust the description and choose Next.

    5. Confirm the transport request and choose Finish.

  2. Activate the copy.

    1. Press Ctrl + F3 to activate the class.

Task 2: Extend the Output

Edit local class LCL_PASSENGER_FLIGHT and extend attribute connection_details with a component duration for the flight duration in minutes. Then edit the GET_DESCRIPTION method and add the flight duration to the output.

Steps

  1. In local class LCL_PASSENGER_FLIGHT, extend attribute connection_details with a component duration of integer type.

    1. In local class LCL_PASSENGER_FLIGHT, locate the definition of structure type st_connection_details.

    2. Adjust the code as follows:

      Code Snippet
      Copy code
      Switch to dark mode
      123456789
      TYPES: BEGIN OF st_connection_details, airport_from_id TYPE /dmo/airport_from_id, airport_to_id TYPE /dmo/airport_to_id, departure_time TYPE /dmo/flight_departure_time, arrival_time TYPE /dmo/flight_departure_time, END OF st_connection_details.
  2. Navigate to the implementation of method GET_DESCRIPTION. At the end of the method, insert an APPEND statement that adds connection_details-duration and a suitable description to r_result .

    1. Add the following code:

      Code Snippet
      Copy code
      Switch to dark mode
      123
      APPEND |Duration: { connection_details-duration } minutes| TO r_result.
  3. Activate the ABAP class.

    1. Press Ctrl + F3.

Task 3: Calculate the Flight Duration

In the class_constructor method, Calculate the flight duration. Use the departure time and arrival time and take into account that the airports lie in different timezones.

Hint

You find the timezones of the airports in database table /LRN/AIRPORT.

Steps

  1. Add a column duration to table-like attribute connections_buffer.

    1. Locate the definition of structure type st_connections_buffer.

    2. Adjust the code as follows:

      Code Snippet
      Copy code
      Switch to dark mode
      1234567891011
      TYPES: BEGIN OF st_connections_buffer, carrier_id TYPE /dmo/carrier_id, connection_id TYPE /dmo/connection_id, airport_from_id TYPE /dmo/airport_from_id, airport_to_id TYPE /dmo/airport_to_id, departure_time TYPE /dmo/flight_departure_time, arrival_time TYPE /dmo/flight_departure_time, END OF st_connections_buffer.
  2. Extend the implementation of the CLASS_CONSTRUCTOR method. At the beginning of the method, read the airport id and timezone of all airports from database table /LRN/AIRPORT into a local internal table airports.

    1. Adjust the code as follows:

      Code Snippet
      Copy code
      Switch to dark mode
      12345678910111213
      CLASS lcl_passenger_flight IMPLEMENTATION. METHOD class_constructor. SELECT FROM /lrn/connection FIELDS carrier_id, connection_id, airport_from_id, airport_to_id, departure_time, arrival_time INTO TABLE @connections_buffer. ENDMETHOD.
  3. At the end of the method, add a loop over the connections_buffer attribute with an inline declared work area (suggested name:connection).

    1. Adjust the code as follows:

      Code Snippet
      Copy code
      Switch to dark mode
      12345678910111213141516
      METHOD class_constructor. SELECT FROM /lrn/airport FIELDS airport_id, timzone INTO TABLE @DATA(airports). SELECT FROM /lrn/connection FIELDS carrier_id, connection_id, airport_from_id, airport_to_id, departure_time, arrival_time INTO TABLE @connections_buffer. ENDMETHOD.
  4. Use ABAP statement CONVERT … INTO UTCLONG to convert the departure time in local time into a universal timestamp. As timezone, use the timezone of the departure airport and as date, the current system date.

    Hint

    Call method cl_abap_context_info=>get_system_date to retrieve the current system date.
    1. Adjust the code as follows:

      Code Snippet
      Copy code
      Switch to dark mode
      12345
      LOOP AT connections_buffer INTO DATA(connection). ENDLOOP.
  5. Do the same with the arrival time and the arrival airport.

    1. Adjust the code as follows:

      Code Snippet
      Copy code
      Switch to dark mode
      12345678910
      LOOP AT connections_buffer INTO DATA(connection). CONVERT DATE today TIME connection-departure_time TIME ZONE airports[ airport_id = connection-airport_from_id ]-timzone INTO UTCLONG DATA(departure_utclong). ENDLOOP.
  6. Fill component duration of work area connection with the difference of the two UTC timestamps in minutes.

    Note

    Use built-in function utclong_diff to calculate the difference. Keep in mind that the function returns the difference in seconds.
    1. Adjust the code as follows:

      Code Snippet
      Copy code
      Switch to dark mode
      123456789101112131415
      LOOP AT connections_buffer INTO DATA(connection). CONVERT DATE today TIME connection-departure_time TIME ZONE airports[ airport_id = connection-airport_from_id ]-timzone INTO UTCLONG DATA(departure_utclong). CONVERT DATE today TIME connection-arrival_time TIME ZONE airports[ airport_id = connection-airport_to_id ]-timzone INTO UTCLONG DATA(arrival_utclong). ENDLOOP.
  7. Finally, use a MODIFY statement to update the current row of internal table connections_buffer with the new content of column duration.

    1. Adjust the code as follows:

      Code Snippet
      Copy code
      Switch to dark mode
      1234567
      connection-duration = utclong_diff( high = arrival_utclong low = departure_utclong ) / 60. ENDLOOP.
  8. Activate and test your code as console app.

    1. Press Ctrl + F3.

    2. Press F9.

Log in to track your progress & complete quizzes