How do I get the current time in Elm 0.17/0.18?

前端 未结 6 1986
悲哀的现实
悲哀的现实 2020-12-14 21:00

I had asked this question already:
How do I get the current time in Elm?

And answered it by writing my own (now deprecated) variant of start-ap

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 21:12

    elm-0.18 full example https://runelm.io/c/72i

    import Time exposing (Time)
    import Html exposing (..)
    import Html.Events exposing (onClick)
    import Task
    
    type Msg
        = GetTime
        | NewTime Time
    
    type alias Model =
        { currentTime : Maybe Time
        }
    
    view : Model -> Html Msg
    view model =
        let
            currentTime =
                case model.currentTime of
                    Nothing ->
                        text ""
    
                    Just theTime ->
                        text <| toString theTime
        in
            div []
                [ button [ onClick GetTime ] [ text "get time" ]
                , currentTime
                ]
    
    update : Msg -> Model -> ( Model, Cmd Msg )
    update msg model =
        case msg of
            GetTime ->
                model ! [ Task.perform NewTime Time.now ]
    
            NewTime time ->
                { model | currentTime = Just time } ! []
    
    main : Program Never Model Msg
    main =
        program
            { init = init
            , update = update
            , view = view
            , subscriptions = always Sub.none
            }
    
    init : ( Model, Cmd Msg )
    init =
        { currentTime = Nothing } ! []
    
    • based on example from http://package.elm-lang.org/packages/elm-lang/core/latest/Task#perform
    • https://github.com/knewter/elm-date-playground
    • https://becoming-functional.com/tasks-in-elm-0-18-2b64a35fd82e

提交回复
热议问题