使用当前日期初始化模型 [英] Initialize model with current date
问题描述
我正在尝试使用当前日期初始化我的模型。我不想使用Native模块。我试图用任务和效果来做。我被困在我的 getCurrentTime
方法。什么是最干净的方式?
I'm trying to initialize my model with the current date. I don't want to use a Native module. I'm trying to do it with Task and Effects. I'm stuck at my getCurrentTime
method. What is the cleanest way?
import Time exposing ( Time )
import StartApp
import Task
import Effects exposing (Never)
import Html exposing ( Html )
app =
StartApp.start
{ init = init
, view = view
, update = update
, inputs = []}
main =
app.html
port tasks : Signal (Task.Task Never ())
port tasks =
app.tasks
type alias Model =
{ clock : Time}
init : (Model, Effects.Effects Action)
init = ((Model ), Effects.none)
type Action = ShowClock
update : Action -> Model -> (Model, Effects.Effects Action)
update action model =
case action of
ShowClock c ->
({ model | clock = c}, Effects.none)
getCurrentTime : Effects.Effects Action
getCurrentTime =
-- stuck here
|> Task.map ShowClock
|> Effects.task
view : Signal.Address Action -> Model -> Html
view address model =
Signal.map Html.text model.clock
It would also be nice to convert the time to a string with "YYYY-MM-DD" format.
推荐答案
一个ELM包可从 http://package.elm- lang.org/packages/evancz/task-tutorial/1.0.3/TaskTutorial ,可以用来获取当前时间。
There is an ELM package available at http://package.elm-lang.org/packages/evancz/task-tutorial/1.0.3/TaskTutorial you can use to get the current time.
首先你需要下载它使用终端或Windows命令中的以下命令更新您的elm-package.json文件:
First you need to download it and update your elm-package.json file using the following command in a terminal or Windows command:
elm-package install evancz/task-tutorial 1.0.3
然后更新你的代码:
getCurrentTime : Effects.Effects Action
getCurrentTime = Effects.task <| Task.map ShowClock ( TaskTutorial.getCurrentTime )
最后,你只需要调用getCurrentTime作为一个特效您的模型将被更新。
Finally, you just have to call getCurrentTime as an Effects Action and your model will be updated.
将您的时间转换为人类可读的日期String可以使用此小帮助函数:
To convert your Time into a human readable date String you can use this little helper function:
toHRDate : Time -> String -- to human readable date
toHRDate t =
let
date = Date.fromTime t
d = toString (Date.day date) -- day
m = toString (Date.month date) -- month
y = toString (Date.year date) -- year
hrd = d ++ "-" ++ m ++ "-" ++ y
in hrd
这篇关于使用当前日期初始化模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!