How do I get the current time in Elm?

后端 未结 8 1361
庸人自扰
庸人自扰 2020-12-03 01:15

I\'m running elm-repl to play around with the language.

I\'d like to see what the current time is. How would I do that? It doesn\'t appear to be possible with the c

8条回答
  •  盖世英雄少女心
    2020-12-03 02:20

    Elm 0.19

    • https://elm-lang.org/examples/time
    • https://elm-lang.org/examples/clock
    • time https://ellie-app.com/3f6X2DW4cbma1
    • Analog svg clock https://ellie-app.com/3dYXjr3bJNWa1

    Below I set inital time as unix time start Time.millisToPosix 0, but you can set it to Nothing and later to Just time or pass it with Flag.

    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
            ]
    

提交回复
热议问题