Technical Articles
ABAP: Converting a date datatype and vice versa
Moderation comment: an updated version of this blog post can found here.
Sometimes formatting a date in ABAP can be very useful:
– The 1st example shows how to convert an internal date (i.e. sy-datum) to an external variable i.e. a char:
- INPUT: 21.06.2018 ( as a date datatype)
- OUTPUT: ‘21.06.2018’ (as character)
DATA date_ext TYPE char10.
CALL FUNCTION 'CONVERT_DATE_TO_EXTERNAL'
EXPORTING
date_internal = sy-datum
IMPORTING
date_external = date_ext
EXCEPTIONS
date_internal_is_invalid = 1
OTHERS = 2.
IF sy-subrc <> 0.
* Implement suitable error handling here
ENDIF.
– The 2nd example shows how to convert an external date format (like a character) to an internal date format:
- INPUT: ‘21.06.2018’ (as character)
- OUTPUT: 21062018 (as a date datatype)
DATA date_int TYPE d.
CALL FUNCTION 'DATE_CONV_EXT_TO_INT'
EXPORTING
i_date_ext = '21.06.2018'
IMPORTING
e_date_int = date_int
EXCEPTIONS
error = 1
OTHERS = 2.
IF sy-subrc <> 0.
* Implement suitable error handling here
ENDIF.
– The 3rd example shows how you can convert a SAP date datatype to a character on your own without the help of an function module:
- INPUT: 21.06.2018 (as sy-datum)
- OUTPUT: ‘21062018’ (as character)
DATA: date(10),
new_date TYPE char10,
day(2),
month(2),
year(4).
WRITE sy-datum TO date.
day(2) = date(2).
month(2) = date+3(2).
year(4) = date+6(4).
new_date = |{ day }| && |{ month }| && |{ year }|.
I'm afraid I need to correct you:
Third example is incorrect and won't work in case date format isn't 'DDMMYYYY' (e.g. date format '2' - 'MM/DD/YYYY').
For the matter of fact, this is a good example why you shouldn't count on self-written code, but rely on official code/API instead.
You shouldn’t be afraid. Coding needs to make fun.
Sometimes SAP Standard needs to be modified with own code fragments.
In the above statement you could easily write the year before the day into the local variable new_date: (the output would be then ‘YYYYMMDD’):
Code can be adjusted to other hard-coded date format, of course.
However, in that case, you won't cover all possible date formats (which can change according to user master record).
you can also use
in the first case.
JNN
This can also be simplified to
Big advantage with this expression is you dont need an intermediate variable if you want to pass a formatted date into a method!
IMHO the output of the second example (DATE_CONV_EXT_TO_INT) is not 21062018 but 20180621