Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elm:Json解码器到目前为止的时间戳_Elm - Fatal编程技术网

Elm:Json解码器到目前为止的时间戳

Elm:Json解码器到目前为止的时间戳,elm,Elm,我正在尝试将时间戳(例如:“1493287973015”)从JSON转换为日期类型 到目前为止,我创建了这个自定义解码器: stringToDate : Decoder String -> Decoder Date stringToDate decoder = customDecoder decoder Date.fromTime 但它不起作用,因为它返回的是结果,而不是日期: Function `customDecoder` is expecting the 2nd argumen

我正在尝试将时间戳(例如:“1493287973015”)从JSON转换为日期类型

到目前为止,我创建了这个自定义解码器:

stringToDate : Decoder String -> Decoder Date
stringToDate decoder =
  customDecoder decoder Date.fromTime
但它不起作用,因为它返回的是结果,而不是日期:

Function `customDecoder` is expecting the 2nd argument to be:

    Time.Time -> Result String a

But it is:

    Time.Time -> Date.Date

有办法进行转换吗?

假设您的JSON实际上是将数值放在引号内(这意味着您正在解析JSON值
“149328797315”
,而不是
149328797315
),您的解码器可能如下所示:

import Json.Decode公开(…)
进口日期
导入字符串
stringToDate:解码器日期。日期
串珠状=
一串
|>然后(\val->
case String.toFloat val的
错误->失败错误

Ok ms->succeed两件事,一个JSON实际上可能以毫秒为整数,而不是字符串,并且自Elm的V0.19以来,情况发生了变化

考虑到您的JSON看起来像

{
    ...
    "someTime": 1552483995395,
    ...
}
然后这将解码为一个时间。Posix:

import Json.Decode as Decode

decodeTime : Decode.Decoder Time.Posix
decodeTime =
    Decode.int
        |> Decode.andThen
            (\ms ->
                Decode.succeed <| Time.millisToPosix ms
            )
import Json.Decode as Decode
解码时间:解码。解码时间。Posix
解码时间=
解码.int
|>解码。然后
(\ms->

Decode.Success谢谢!我成功了。用Elm解码JSON并不容易。我甚至不会说这不容易。如果你有命令式的背景,这是不熟悉的。这种解析在函数式语言中相当常见;它被称为解析器组合器……如果它是UNIX时间戳,请记住……如果这是一个UNIX时间戳,请记住。。。