首页 > 解决方案 > 在初始化 ELM 0.19 中设置当前时间

问题描述

我从 JS 获取输入 JSON 数据。这是一个简单的对象,其中有一个格式为“DD.MM.YYYY”的日期——只是一个字符串。

如果对象中没有 dateStart,我必须将其替换为当前日期(在 withDefault 中)。

paramsDecoder : Decode.Decoder Params
paramsDecoer =
    Decode.succeed Params
        |> Decode.andMap (Decode.field "dateStart" (Decode.string) |> (Decode.withDefault) "")
        |> Decode.andMap (Decode.field "dateEnd" (Decode.string)   |> (Decode.withDefault) "")
        |> Decode.andMap (Decode.field "country" (Decode.string)   |> (Decode.withDefault) "spain")

我怎样才能在 ELM 中做到这一点?时区并不重要,总是等于同一个地区。

我找到了 Time.now Time.zone 用法的示例,但是有时间进入 Update 并且为时已晚。

标签: timeelm

解决方案


我分两部分解决了这个问题:

第1部分

初始化时将当前时间发送到 Elm,使用标志:

Elm.Main.init({flags: Date.now()});

并将其放入您的模型中:

import Time exposing (Posix, millisToPosix)

type alias Model = { now : Time.Posix, ... }

init : Int -> (Model, Cmd Msg)
init time = (Model (millisToPosix time), Cmd.none)

对于您的用例,您可以使用withDefault model.now.

第2部分

第 1 部分中的解决方案将仅设置now为页面加载的时间。

如果你想保持最新的时间,你可以Time.every用来更新你的模型:

import Time exposing (Posix, millisToPosix, every)

timeOutCheck : Sub Msg
timeOutCheck = Time.every 250 UpdateTimeNow

type Msg = UpdateTimeNow Posix | ...

update msg model = case msg of
  UpdateTimeNow time = { model | now = time }
  ...

这将确保now不超过当前时间 250 毫秒。您可以250根据需要进行更改。


推荐阅读