Saturday, August 29, 2009

Date and Time Calculations

Date and time fields have character types, not numeric ones. However, you can still use date and time fields in numeric operations. To allow you to do so, the system performs automatic type conversions. You may also find it useful to use offset and length specifications when using date and time fields in calculations.


Example of a date calculation:

DATA: ULTIMO TYPE D.

ULTIMO = SY-DATUM.
ULTIMO+6(2) = '01'. " = first day of this month
ULTIMO = ULTIMO - 1. " = last day of last month

Here, the last day of the previous month is assigned to the date field ULTIMO.

1. ULTIMO is filled with the present date.

2. Using an offset specification, the day is changed to the first day of the current month.

3. 1 is subtracted from ULTIMO. Its contents are changed to the last day of the previous month. Before performing the subtraction, the system converts ULTIMO to the number of days since 01.01.0001 and converts the result back to a date.


Example of a time calculation:

DATA: DIFF TYPE I,
SECONDS TYPE I,
HOURS TYPE I.

DATA: T1 TYPE T VALUE '200000',
T2 TYPE T VALUE '020000'.

DIFF = T2 - T1.
SECONDS = DIFF MOD 86400.
HOURS = SECONDS / 3600.

The number of hours between 02:00:00 and 20:00:00 is calculated.

1. First, the difference between the time fields is calculated. This is -64800, since T1 and T2 are converted internally into 72000 and 7200 respectively.

2. Second, with the operation MOD, this negative difference is converted to the total number of seconds. A positive difference would be unaffected by this calculation.

3. Third, the number of hours is calculated by dividing the number of seconds by 3600.

The last three lines can be replaced by the following line

HOURS = ( ( T2 - T1 ) MOD 86400 ) / 3600.

No comments:

Tutorials on SAP-ABAP

Adobe Interactive Forms Tutorials

Business Server Pages (BSP)

Userexits/BADIs

Web Dynpro for ABAP (Step by step procedure for web dynpro,Tutorials on Web Dynpro,)

ALV Tutorials

goodsites