Time in Elm

Lucamug
8 min readAug 19, 2019

Handling time in Elm seems to be a scaring thing for beginners.

In Elm is not possible to have a function that return the present time because that would not be a pure function and all functions must be pure.

Such a function is not pure because the output is different every time we call it while pure function need to always return the same output given the same arguments.

The function will “contaminate” also any other pure function that call it making your entire code difficult to reason about and to test.

But is this a real issue?

Let’s answer this question building a simple page that display the current Posix time (also called Unix time or Epoch time).

I assume that you are have some familiarity with The Elm Architecture. Is not have look at the official guide

First of all, we need a place to store this Posix value. So let’s assume that the model of our app is Maybe Time.Posix. "Maybe" because when the app start, we still don't have the value. We could pass as a flag but let's keep the things simple.

The official elm/time library has the function Time.now that return a Task x Posix.

Time.now : Task x Time.Posix

A Task is an asynchronous operations that may fail. We can perform this task during the initialization of our app:

init _ =
( Nothing
, Task.perform GotTime Time.now
)

Note that we initialize the model with Nothing because we don't have the Posix yet. The command Task.perform GotTime Time.now is telling the Elm runtime "Please, (yes, commands always start with please) get the time now and when you get it, send it back to me using the message GotTime".

When we get the time back, we just simply save into the model:

update msg model =
case msg of
GotTime timeNow ->
( Just timeNow, Cmd.none )

We can now use it the way we want, for example:

view model =
text <|
case model of
Just timeNow ->
"Posix time now: " ++ (String.fromInt <|
Time.posixToMillis timeNow)
Nothing ->

--

--