Time in COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. TIME-EXAMPLE.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-CURRENT-DATE.
05 WS-YEAR PIC 9(4).
05 WS-MONTH PIC 9(2).
05 WS-DAY PIC 9(2).
05 WS-HOUR PIC 9(2).
05 WS-MINUTE PIC 9(2).
05 WS-SECOND PIC 9(2).
05 WS-HUNDREDTH PIC 9(2).
01 WS-FORMATTED-DATE PIC X(21).
01 WS-SPECIFIC-DATE PIC 9(14).
01 WS-WEEKDAY PIC 9.
01 WS-WEEKDAY-NAME PIC X(9).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM GET-CURRENT-TIME
PERFORM DISPLAY-CURRENT-TIME
PERFORM CREATE-SPECIFIC-TIME
PERFORM EXTRACT-TIME-COMPONENTS
PERFORM GET-WEEKDAY
PERFORM COMPARE-TIMES
STOP RUN.
GET-CURRENT-TIME.
ACCEPT WS-CURRENT-DATE FROM DATE YYYYMMDD.
ACCEPT WS-CURRENT-DATE FROM TIME.
DISPLAY-CURRENT-TIME.
MOVE FUNCTION CURRENT-DATE TO WS-FORMATTED-DATE.
DISPLAY "Current time: " WS-FORMATTED-DATE.
CREATE-SPECIFIC-TIME.
MOVE 20091117203458 TO WS-SPECIFIC-DATE.
DISPLAY "Specific time: " WS-SPECIFIC-DATE.
EXTRACT-TIME-COMPONENTS.
DISPLAY "Year: " WS-YEAR.
DISPLAY "Month: " WS-MONTH.
DISPLAY "Day: " WS-DAY.
DISPLAY "Hour: " WS-HOUR.
DISPLAY "Minute: " WS-MINUTE.
DISPLAY "Second: " WS-SECOND.
GET-WEEKDAY.
COMPUTE WS-WEEKDAY = FUNCTION MOD (WS-DAY + 2 * WS-MONTH +
(3 * (WS-MONTH + 1) / 5) + WS-YEAR + (WS-YEAR / 4) -
(WS-YEAR / 100) + (WS-YEAR / 400) + 2) 7
EVALUATE WS-WEEKDAY
WHEN 0 MOVE "Sunday" TO WS-WEEKDAY-NAME
WHEN 1 MOVE "Monday" TO WS-WEEKDAY-NAME
WHEN 2 MOVE "Tuesday" TO WS-WEEKDAY-NAME
WHEN 3 MOVE "Wednesday" TO WS-WEEKDAY-NAME
WHEN 4 MOVE "Thursday" TO WS-WEEKDAY-NAME
WHEN 5 MOVE "Friday" TO WS-WEEKDAY-NAME
WHEN 6 MOVE "Saturday" TO WS-WEEKDAY-NAME
END-EVALUATE
DISPLAY "Weekday: " WS-WEEKDAY-NAME.
COMPARE-TIMES.
IF WS-SPECIFIC-DATE < FUNCTION CURRENT-DATE
DISPLAY "Specific time is before current time"
ELSE
DISPLAY "Specific time is after or equal to current time"
END-IF.
This COBOL program demonstrates various time-related operations:
We start by getting the current time using the
ACCEPT
statement withDATE
andTIME
.We display the current time in a formatted manner.
We create a specific time (November 17, 2009, 20:34:58) for comparison.
We extract various components of the time (year, month, day, hour, minute, second) and display them.
We calculate the day of the week for the current date using a formula and display it.
Finally, we compare the specific time with the current time.
Note that COBOL doesn’t have built-in functions for all the time operations that are available in more modern languages. For example, there’s no direct way to calculate duration between two times or add/subtract durations. These operations would require more complex calculations in COBOL.
To run this COBOL program, you would typically compile it and then execute the resulting binary. The exact commands depend on your COBOL compiler, but it might look something like this:
$ cobc -x time-example.cob
$ ./time-example
This will compile the COBOL source code into an executable and then run it, displaying the time-related information.