Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[ABAP] Quick way to get last year’s BEGDA and ENDDA

Using method get_current_year of class cl_hcmfab_reporting_utility you can get BEGDA and ENDDA of the current year, e.g. 01.01.2025 and 31.12.2025

  CALL METHOD cl_hcmfab_reporting_utility=>get_current_year
    EXPORTING
      iv_date  = sy-datlo
    IMPORTING
      ev_begda = DATA(begda)
      ev_endda = DATA(endda).

I couldn’t find a similar method to get the same for the last year. But I could solve the problem with three simple lines.

DATA(last_year) = conv d( sy-datlo - 365 ).
DATA(begda)     = last_year(4) && '0101'.
DATA(endda)     = last_year(4) && '1231'.

After that, I asked Perplexity and it gave me a similar result.

DATA(lv_last_year) = sy-datum+0(4) - 1.
DATA(lv_begda)     = |{ lv_last_year }0101|.
DATA(lv_endda)     = |{ lv_last_year }1231|.

Using this method, you could even reduce it to two lines, and it would still be easy to read.

DATA(begda)  = |{ sy-datum(4) - 1 }0101|.
DATA(endda)  = |{ sy-datum(4) - 1 }1231|.

[ABAP] Get the last day of the previous month

I recently had to find the last day of the previous month. I found the Method get_last_day_prev_month of class cl_bs_period_toolset_basics doing the job. The actual logic is super simple:

  rv_date      = iv_date.
  rv_date+6(2) = '01'.
  rv_date      = rv_date - 1.

That’s why I thought about whether I needed a separate method at all, or whether I could do it directly in a one-liner. My first idea was to use the LET operator in combination with CONV (Option 2). This works, but does not look very intuitive, and I noticed it can be done even simpler without using LET (Option 3). And if you already have a typed variable, you can do it even shorter with a single CONV (Option 4).

* Option 1
DATA(date_1) = cl_bs_period_toolset_basics=>get_last_day_prev_month( sy-datum ).

*Option 2
DATA(date_2) = CONV d( LET x = CONV d( sy-datum(6) && '01' ) IN x - 1 ).

*Option 3
DATA(date_3) = CONV d( CONV d( sy-datum(6) && '01' ) - 1 ).

* Option 4
DATA date_4 TYPE datum.
date_4 = CONV d( sy-datum(6) && '01' ) - 1.

cl_demo_output=>write_data( date_1 ).
cl_demo_output=>write_data( date_2 ).
cl_demo_output=>write_data( date_3 ).
cl_demo_output=>write_data( date_4 ).
cl_demo_output=>display( ).

All in all, I have to say that using the get_last_day_prev_month method is still the best solution as it is much more readable.