Skip to content

Instantly share code, notes, and snippets.

@msszczep
Created Nov 24, 2019
Embed
What would you like to do?
Improved Time in Elm
-- Show the current time in your time zone.
--
-- Read how it works:
-- https://guide.elm-lang.org/effects/time.html
--
-- For an analog clock, check out this SVG example:
-- https://elm-lang.org/examples/clock
--
import Browser
import Html exposing (..)
import Task
import Time
-- MAIN
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ zone : Time.Zone
, time : Time.Posix
}
init : () -> (Model, Cmd Msg)
init _ =
( Model Time.utc (Time.millisToPosix 0)
, Task.perform AdjustTimeZone Time.here
)
-- UPDATE
type Msg
= Tick Time.Posix
| AdjustTimeZone Time.Zone
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Tick newTime ->
( { model | time = newTime }
, Cmd.none
)
AdjustTimeZone newZone ->
( { model | zone = newZone }
, Cmd.none
)
zeroPad : String -> String
zeroPad s =
let
len = String.length s
in
case len of
1 -> "0" ++ s
_ -> s
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every 1000 Tick
-- VIEW
view : Model -> Html Msg
view model =
let
hour = Time.toHour model.zone model.time |> String.fromInt |> zeroPad
minute = Time.toMinute model.zone model.time |> String.fromInt |> zeroPad
second = Time.toSecond model.zone model.time |> String.fromInt |> zeroPad
in
h1 [] [ text (hour ++ ":" ++ minute ++ ":" ++ second) ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment