Skip to content

Instantly share code, notes, and snippets.

@PascalLeMerrer
Created February 18, 2021 17:34
Show Gist options
  • Save PascalLeMerrer/fd9574a6766b30b1732fdc7d498c2fbe to your computer and use it in GitHub Desktop.
Save PascalLeMerrer/fd9574a6766b30b1732fdc7d498c2fbe to your computer and use it in GitHub Desktop.
Current time and timezone in Elm 0.19
module Main exposing (main)
import Browser
import Html exposing (Html)
import Task
import Time exposing (Posix)
main : Program () Model Msg
main =
Browser.element
{ init = \_ -> init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
-- MODEL
type alias Model =
{ zone : Time.Zone
, now : Posix
}
init : ( Model, Cmd Msg )
init =
( Model Time.utc (Time.millisToPosix 0), Task.perform Zone Time.here )
-- UPDATE
type Msg
= Zone Time.Zone
| Now Posix
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Zone zone ->
( { model | zone = zone }, Task.perform Now Time.now )
Now now ->
( { model | now = now }, Cmd.none )
-- VIEW
formatTime zone posix =
(String.padLeft 2 '0' <| String.fromInt <| Time.toHour zone posix)
++ ":"
++ (String.padLeft 2 '0' <| String.fromInt <| Time.toMinute zone posix)
++ ":"
++ (String.padLeft 2 '0' <| String.fromInt <| Time.toSecond zone posix)
view : Model -> Html Msg
view model =
Html.div []
[ Html.text <| formatTime model.zone model.now
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment