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…

--

--