time - 在初始化 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 并且为时已晚。
解决方案
我分两部分解决了这个问题:
第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
根据需要进行更改。
推荐阅读
- android - APK 或 App Bundle 可用于 64 位设备,但它们只有 32 位本机代码 Unity Play 商店错误
- javascript - UglifyJs 意外标记:关键字«const» Webpack 4
- c# - 自 16.2.x 起,Visual Studio 2019 测试资源管理器切换到“OR”过滤
- android - 如何在 build.gradle 文件中使用 assemblerelease
- python - 无法在 Tkinter 的主窗口中添加滚动条
- elasticsearch - 如何在 Elasticsearch 中优先考虑第一个单词匹配而不是第一个字符?
- haskell - 如何将树数据存储在列表中?
- bash - 将 awk 输出分配给变量
- database - 具有迁移策略的开放资产数据库
- flutter - 添加 Firestore 文档时更新 ListView.builder itemCount