BudiBadu Logo
Samplebadu

COBOL by Example: Dates and Times

COBOL 2002

Retrieving current system date and time with CURRENT-DATE intrinsic function, formatting dates using structured group items with YYYY MM DD fields, displaying time components for hours minutes seconds, and handling timezone offsets.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. DATE-TIME.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  CURRENT-DT.
           05  YYYY    PIC 9(4).
           05  MM      PIC 99.
           05  DD      PIC 99.
           05  HRS     PIC 99.
           05  MINS    PIC 99.
           05  SEC     PIC 99.
           05  MS      PIC 99.
       
       PROCEDURE DIVISION.
           MOVE FUNCTION CURRENT-DATE TO CURRENT-DT.
           DISPLAY "Date: " YYYY "-" MM "-" DD.
           DISPLAY "Time: " HRS ":" MINS ":" SEC.
           STOP RUN.

Explanation

Handling dates correctly is critical in business applications. The intrinsic function CURRENT-DATE returns a 21-character alphanumeric string containing the current date, time, and offset from GMT. This standardizes date retrieval across different platforms.

In this example, we define a group item CURRENT-DT that matches the layout of the returned string. By moving the function result into this group item, COBOL automatically parses the string into its component parts (Year, Month, Day, etc.), making them easy to access individually.

This approach avoids the need for complex string parsing logic. You can simply access YYYY, MM, or DD directly. Note that the returned time includes hundredths of a second and the time zone offset, which are useful for logging and global applications.

Code Breakdown

15
MOVE FUNCTION CURRENT-DATE TO CURRENT-DT. Fetches the system timestamp and parses it into our data structure in one step.
16
DISPLAY "Date: " YYYY "-" MM "-" DD. We can now use the individual fields like YYYY and MM directly.
17
DISPLAY "Time: " HRS ":" MINS ":" SEC. Similarly, we can access the time components.