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.

import Time
import Task
import Html exposing (Html, div, text)
import Html.Attributes exposing (style)

main : Program () Model Msg
main =
    Html.program
        { init = init
        , view = view
        , update = update
        , subscriptions = always Sub.none
        }

type alias Model =
    { now : Time.Posix
    }

type Msg
    = NewTime Time.Posix

init : ( Model, Cmd Msg )
init =
    ( { now = Time.millisToPosix 0 }
    , Task.perform NewTime Time.now
    )

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NewTime time ->
            ( { model | now = time }, Cmd.none )

view : Model -> Html Msg
view model =
    div []
        [ div [] [ text <| "Current time: " ++ Debug.toString model.now ]
        , div [] [ text <| "Seconds since epoch: " ++ String.fromInt (Time.posixToMillis model.now // 1000) ]
        , div [] [ text <| "Milliseconds since epoch: " ++ String.fromInt (Time.posixToMillis model.now) ]
        ]

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.