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 F#.
To run the program, save it as Epoch.fs and use the F# compiler:
In F#, we use the System.DateTime struct to work with dates and times. The DateTime.UtcNow property gives us the current UTC time. To get the Unix timestamp, we subtract the Unix epoch (January 1, 1970) from the current time and convert the result to seconds, milliseconds, or an approximation of nanoseconds.
F# doesn’t have built-in methods for Unix time like Unix(), UnixMilli(), or UnixNano(), so we perform the calculations manually. Also, F# (and .NET in general) doesn’t provide nanosecond precision, so the nanosecond calculation is an approximation.
To convert back from a Unix timestamp to a DateTime, we add the number of seconds (or milliseconds for the nanosecond case) to the Unix epoch.
Next, we’ll look at another time-related task: time parsing and formatting in F#.