Epoch in Elm
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 Elm.
In Elm, we use the Time
module to work with time-related operations. The Time.now
function returns the current time as a Task
, which we can convert to a Cmd
using Task.perform
.
We use Time.posixToMillis
to get the number of milliseconds since the Unix epoch. To get seconds, we divide the result by 1000.
Elm doesn’t have a built-in way to get nanoseconds since the epoch, so we’ve omitted that part.
To run this program, you would typically compile it to JavaScript and run it in a web browser. The output would be displayed on the web page, showing the current time and the number of seconds and milliseconds since the Unix epoch.
Note that Elm is a functional language designed for building web applications, so the structure and execution model are quite different from imperative languages. This example creates a simple Elm application that displays the time information when loaded in a web browser.
Next, we’ll look at another time-related task: time parsing and formatting.