The function module HR_HK_DIFF_BT_2_DATES in SAP ABAP can be used to calculate the difference between 2 dates.
HR_HK_DIFF_BT_2_DATES
Please check the following program. Experiment with the OUTPUT FORMAT (Example '01', '02', '03', '04', 05'). Make sure that Date1 is greater than Date2
REPORT ZEX_DIFFBETW2DATES .
Data: d_date1 like P0001-BEGDA,
d_date2 like P0001-BEGDA,
d_yrs like P0347-SCRYY,
d_months like P0347-SCRMM,
d_days like P0347-SCRDD.
* Date1 should be greater than date 2
d_date1 = '20050101'.
d_date2 = '20000104'.
* This function calculates the diference between date 1 and date 2
CALL FUNCTION 'HR_HK_DIFF_BT_2_DATES'
EXPORTING
DATE1 = d_date1
DATE2 = d_date2
OUTPUT_FORMAT = '05'
IMPORTING
YEARS = d_yrs
MONTHS = d_months
DAYS = d_days
EXCEPTIONS
INVALID_DATES_SPECIFIED = 1
OTHERS = 2.
IF SY-SUBRC <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
write:/ 'Years = ', d_yrs, 'Months = ', d_months, 'Days = ', d_days.
Data: d_date1 like P0001-BEGDA,
d_date2 like P0001-BEGDA,
d_yrs like P0347-SCRYY,
d_months like P0347-SCRMM,
d_days like P0347-SCRDD.
* Date1 should be greater than date 2
d_date1 = '20050101'.
d_date2 = '20000104'.
* This function calculates the diference between date 1 and date 2
CALL FUNCTION 'HR_HK_DIFF_BT_2_DATES'
EXPORTING
DATE1 = d_date1
DATE2 = d_date2
OUTPUT_FORMAT = '05'
IMPORTING
YEARS = d_yrs
MONTHS = d_months
DAYS = d_days
EXCEPTIONS
INVALID_DATES_SPECIFIED = 1
OTHERS = 2.
IF SY-SUBRC <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
write:/ 'Years = ', d_yrs, 'Months = ', d_months, 'Days = ', d_days.
The output of the the above program is as follows.
Difference Between 2 dates
Years = 4.0000 Months = 11.0000 Days = 29
Years = 4.0000 Months = 11.0000 Days = 29
This function is very useful, but you have to be careful, because every month is calculated there with 31 days. As we all know, February has 28 or 29 days and April, June etc. have 30 days, so you have to make some extra lines in the source code:
ReplyDeleteIf month (something like date+4(2) ) is equal to 04 or 06 or 09 or 11, then you have to substract one from your result in days.
If month is equal to 02, then you have to substract two or three from you result in days.