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 Haskell.
In Haskell, we use the Data.Time library to work with time-related functions. The getPOSIXTime function returns the current time as the number of seconds since the Unix epoch.
We use getCurrentTime to get the current time, and formatTime to format it as a string.
To get the elapsed time since the Unix epoch in seconds, milliseconds, or nanoseconds, we multiply the POSIX time by the appropriate factor and convert it to an integer.
You can also convert integer seconds or nanoseconds since the epoch into the corresponding UTCTime. In this example, we use posixSecondsToUTCTime to perform this conversion.
Here’s an example of what the output might look like:
Next, we’ll look at another time-related task: time parsing and formatting.