Epoch in COBOL
A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in COBOL.
In COBOL, we use the FUNCTION CURRENT-DATE
to get the current date and time. This function returns a string containing the current date and time components, which we move into our WS-CURRENT-DATE
structure.
To calculate the number of seconds since the Unix epoch (January 1, 1970), we first convert the date to days using FUNCTION INTEGER-OF-DATE
, multiply by the number of seconds in a day (86400), and add the time components. We then subtract the number of seconds from January 1, 1970, to January 1, 1601 (which is 2208988800) because COBOL’s date functions typically use 1601 as the base year.
For milliseconds, we multiply the seconds by 1000 and add the hundredths of a second multiplied by 10.
For nanoseconds, we multiply the milliseconds by 1,000,000.
Note that COBOL doesn’t have built-in functions for Unix time calculations, so we have to perform these calculations manually. Also, the precision of these calculations may be limited by the capabilities of the COBOL compiler and the underlying system.
To run the program, you would typically compile it and then execute the resulting program:
The output will vary based on the current date and time when you run the program.
COBOL doesn’t have a direct equivalent to Go’s time.Unix()
function for converting Unix timestamps back into dates. To achieve this, you would need to write a custom function to perform the reverse calculations.
Next, we’ll look at another time-related task: date formatting and parsing in COBOL.