Source : https://stackoverflow.com/questions/29453679/how-do-i-get-the-current-time-in-elm/52156804#52156804
Created
February 18, 2021 17:34
-
-
Save PascalLeMerrer/fd9574a6766b30b1732fdc7d498c2fbe to your computer and use it in GitHub Desktop.
Current time and timezone in Elm 0.19
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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