How do I get the current time in Elm?

后端 未结 8 1362
庸人自扰
庸人自扰 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条回答
  •  旧时难觅i
    2020-12-03 02:15

    The answer (for 0.18) from Simon H got me started in the right direction, but I did have some trouble working out how to actually do something with that time. (user2167582 adds a comment to Simon's answer which asks the same thing: how do you 'get the time out?').

    My specific problem was that I wanted to include the current time in the body of a POST to the server.

    I eventually solved that and was quite pleased with the end result -- the use of Task.andThen meant that I in my postTime function I can just use timestamp as a 'regular' float-valued parameter (which it is when the task gets run, I suppose).

    My full SO answer is here.

    Below is the solution I came up with and here it is in Ellie:

    module Main exposing (..)
    
    import Html exposing (..)
    import Html.Events exposing (..)
    import Http
    import Json.Decode as JD
    import Json.Encode as JE
    import Task
    import Time
    
    
    type alias Model =
        { url : String
        }
    
    
    type Msg
        = PostTimeToServer
        | PostDone (Result Http.Error String)
    
    
    update : Msg -> Model -> ( Model, Cmd Msg )
    update msg model =
        case msg of
            PostTimeToServer ->
                ( model, postTimeToServer model.url )
    
            PostDone _ ->
                ( model, Cmd.none )
    
    
    view : Model -> Html Msg
    view model =
        div []
            [ div []
                [ button [ onClick PostTimeToServer ] [ Html.text "POST the current time." ]
                ]
            ]
    
    
    postTimeToServer : String -> Cmd Msg
    postTimeToServer url =
        let
            getTime =
                Time.now
    
            postTime t =
                JD.string
                    |> Http.post url (JE.float t |> Http.jsonBody)
                    |> Http.toTask
    
            request =
                getTime                                            <<-- Here is
                    |> Task.andThen postTime                       <<-- the key bit.
        in
            Task.attempt PostDone request
    
    
    main =
        Html.program
            { init = ( Model "url_here", Cmd.none )
            , update = update
            , view = view
            , subscriptions = always Sub.none
            }
    

提交回复
热议问题