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 OCaml.
In OCaml, we use the Unix module to work with time-related functions. The gettimeofday function returns the current time as a float representing seconds since the Unix epoch.
We can then use this value to calculate seconds, milliseconds, and nanoseconds. To convert back to a time structure, we use the localtime function.
To run the program, save it as epoch.ml and use the OCaml compiler:
Note that the exact output will depend on when you run the program.
Next, we’ll look at another time-related task: time parsing and formatting.