How to Calculate Date Difference in SAP ABAP

In SAP ABAP, you can calculate the difference between two dates (in days, months, or years) using different methods.


1. Simple Date Difference in Days

ABAP allows you to directly subtract two date fields.

DATA: lv_date1 TYPE sy-datum,
lv_date2 TYPE sy-datum,
lv_diff TYPE i.
lv_date1 = '20240310'. " 10th March 2024
lv_date2 = '20240301'. " 1st March 2024
lv_diff = lv_date1 - lv_date2.
WRITE: 'Difference in days:', lv_diff.

Works with standard date format (YYYYMMDD) ✅ Returns positive or negative values depending on date order


2. Difference in Months and Years

For months and years, you can use the function module HR_HK_DIFF_BT_2_DATES.

DATA: lv_date1 TYPE sy-datum,
lv_date2 TYPE sy-datum,
lv_years TYPE i,
lv_months TYPE i,
lv_days TYPE i.
lv_date1 = '20240310'. " 10th March 2024
lv_date2 = '20210305'. " 5th March 2021
CALL FUNCTION 'HR_HK_DIFF_BT_2_DATES'
EXPORTING
date1 = lv_date1
date2 = lv_date2
IMPORTING
years = lv_years
months = lv_months
days = lv_days.
WRITE: 'Difference:', lv_years, 'Years,', lv_months, 'Months,', lv_days, 'Days'.

Accurate calculation of years, months, and days ✅ Handles varying month lengths


3. Using DAYS_BETWEEN_TWO_DATES Function Module

If you’re dealing with factory calendars, you can use:

DATA: lv_days TYPE i.
CALL FUNCTION 'DAYS_BETWEEN_TWO_DATES'
EXPORTING
date_1 = '20240310'
date_2 = '20240301'
IMPORTING
days = lv_days.
WRITE: 'Days difference:', lv_days.

Useful when working with business daysConsiders factory calendar settings


4. Using Class CL_ABAP_TSTMP for More Precision

If you’re working with timestamps and need precise time differences, use:

DATA: lv_date1 TYPE timestamp,
lv_date2 TYPE timestamp,
lv_diff TYPE int8.
lv_date1 = '20240310120000'. " 10th March 2024, 12:00:00
lv_date2 = '20240309180000'. " 9th March 2024, 18:00:00
lv_diff = cl_abap_tstmp=>subtract(
i_tstmp1 = lv_date1
i_tstmp2 = lv_date2 ).
WRITE: 'Difference in seconds:', lv_diff.

Precise to the secondWorks with timestamps (YYYYMMDDHHMMSS)


Best Method to Use?

ScenarioRecommended Method
Difference in daysdate1 - date2
Difference in years, months, and daysHR_HK_DIFF_BT_2_DATES
Difference in business daysDAYS_BETWEEN_TWO_DATES
Difference in timestamps (seconds)CL_ABAP_TSTMP=>SUBTRACT