Sunday, September 27, 2009

Date formatting/processing in SAP

Format of the date depends on various factors, to give you example it can depend on the country, type of business and even on personal choice. Internally SAP stores the date in YYYYMMDD format in char length 8 type field. Storing the date in this format makes it format independent, take less space to store and easy to sort and easy to compare. Although date is stored in ‘YYYYMMDD’ format but it is never displayed to user as it is (unless intended). While displaying the date to user SAP always takes care of date format active for user. Statements WRITE automatically display date field based on user date format. This statement is particularly important if you are using a date in BDC. Always remember to format date using WRITE statement before pass date to screen in BDC mode. A user can change the date format for his/her profile using transaction SU3. Centrally it can change by administrators using SU01/SU10.

Basic addition and subtracts in days work perfectly fine on date type field in SAP. It takes care of number of days in month and leap year. For example, adding 5 to 29-dec-2009 will return 03-Jan-2010. And subtracting 1-Mar-2009 and 27-Feb-2009 will result in 2. Remember you can always determine the year month and day of a date variable by extracting the correct characters. So if V_DATE is your date variant in SAP then

Year = V_DATE(4).
Month = V_DATE+4(2).
Day = V_DATE+6(2).

It worth noting that table T247 stores the short and Long description of month or you can use function module MONTH_NAMES_GET for the same.

Related Blogs.

First Day and Last Day of Month
Simple Date Formatting
FM ADD_TIME_TO_DATE

First and Last Day of the Month

Getting first day of the month is easy as first day of month is always 01, so you can replace the day (DD) part of the date field with 01 and you are done. However getting the last day of month is but tricky as last can 28, 30 or 31 depending on what month and leap year. Easier way to find the last day of month is subtract 1 from 1 days of next month.


REPORT zpwtest .
 
DATA : v_date TYPE syst-datum ,
v_first TYPE syst-datum ,
v_last TYPE syst-datum .
 
v_date = sy-datum .
 
*First day of month will be

CONCATENATE v_date(4) v_date+4(2) '01' INTO v_first .
WRITE : / 'First day of month : ' , v_first .
 

*And to find last day, first get a date in next month

IF v_date+4(2) > 15 .
v_date = v_date + 20 .
ELSE.
v_date = v_date + 30 .
ENDIF.

*Then get first day of next month

CONCATENATE v_date(4) v_date+4(2) '01' INTO v_last .

*Subtract one day will be last day of previous month

v_last = v_last - 1 .
WRITE : / 'Last day of month : ' , v_last .