gpt4 book ai didi

elm - 如何在 elm 中获取当前日期?

转载 作者:行者123 更新时间:2023-12-04 16:09:03 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何在版本 .17 的 elm 中获取当前日期。我看到他们在 .17 中添加了一个 Date 模块,但我没有找到任何关于如何使用它的示例。有没有人知道如何做到这一点?

编辑:在尝试改造这个解决方案时,我遇到了另一个绊脚石。我正在尝试触发设置日期,然后调用另一个 Msg 来做其他事情。但我还是要{}约会。

import Html.App as App
import Html exposing (..)
import Time exposing (Time)
import Task
import Date exposing (Date)
import Html.Events exposing (onClick)
import Html.Attributes exposing (..)

type alias Model =
{currentDate : Maybe Date}

type Msg =
SetDate (Maybe Date)
| TriggerDateSet

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
SetDate date ->
({model | currentDate = date}, Cmd.none)
TriggerDateSet ->
(model, now)

view : Model -> Html Msg
view model =
div []
[ div []
[ button [onClick TriggerDateSet] [] ]
, div [] [ text <| "(Optional) time at program launch was " ++ toString model ]
]

now : Cmd Msg
now =
Task.perform (always (SetDate Nothing)) (Just >> SetDate) Date.now

main : Program Never
main =
App.program
{ init = ( Model Nothing, now )
, view = view
, subscriptions = always Sub.none
, update = update
}

最佳答案

您需要 now 任务或 every 订阅 Time .

这是一个使用前者用当前时间初始化模型的示例。

import Html.App as App
import Html exposing (..)
import Time exposing (Time)
import Task


type alias Model =
Maybe Time


type Msg =
SetTime (Maybe Time)


update : Msg -> Model -> (Model, Cmd Msg)
update (SetTime time) _ =
(time, Cmd.none)


view : Model -> Html Msg
view model =
div [] [ text <| "(Optional) time at program launch was " ++ toString model ]


now : Cmd Msg
now =
Task.perform (Just >> SetTime) Time.now


main : Program Never
main =
App.program
{ init = ( Nothing, now )
, view = view
, subscriptions = always Sub.none
, update = update
}

关于elm - 如何在 elm 中获取当前日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37910613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com