Elm:Json解码器时间戳记至今 [英] Elm: Json decoder timestamp to Date
问题描述
我正在尝试将时间戳(例如: 1493287973015)从JSON转换为日期类型。
I'm trying to convert a timestamp (ex: "1493287973015") from a JSON to a Date type.
到目前为止,我已经创建了此自定义解码器:
So far I created this custom decoder:
stringToDate : Decoder String -> Decoder Date
stringToDate decoder =
customDecoder decoder Date.fromTime
无法工作,因为它已返回结果,而不是日期:
But it doesn't work because it has return a Result, not a Date:
Function `customDecoder` is expecting the 2nd argument to be:
Time.Time -> Result String a
But it is:
Time.Time -> Date.Date
是否可以进行转换?
推荐答案
假设您的JSON实际上是将数字值放在引号内(这意味着您正在解析JSON值 1493287973015
,而不是 1493287973015
),则您的解码器可能如下所示:
Assuming your JSON is actually placing the numeric value inside quotes (meaning you are parsing the JSON value "1493287973015"
and not 1493287973015
), your decoder could look like this:
import Json.Decode exposing (..)
import Date
import String
stringToDate : Decoder Date.Date
stringToDate =
string
|> andThen (\val ->
case String.toFloat val of
Err err -> fail err
Ok ms -> succeed <| Date.fromTime ms)
请注意, stringToDate
没有传递任何参数,与您尝试将解码器字符串
作为参数传递的示例相反。
Notice that stringToDate
doesn't get passed any parameters, as opposed to your example in which you were attempting to pass a Decoder String
as a parameter. That's not quite how decoders work.
相反,这可以通过在更原始的解码器上构建来完成,在这种情况下,我们从解码器 string
from Json.Decode
。
Instead, this can be done by building upon more primitive decoders, in this case, we start with the decoder string
from Json.Decode
.
andThen
部分然后获取解码器给出的字符串值,并尝试将其解析为浮点型。如果它是有效的 Float
,则将其输入到 Date.fromTime
中,否则将失败。
The andThen
portion then takes the string value given by the decoder, and tries to parse it to a float. If it is a valid Float
, it is fed into Date.fromTime
, otherwise, it's a failure.
失败
和 成功
函数将您要处理的正常值包装到 Decoder Date.Date中。
上下文,以便可以将其返回。
The fail
and succeed
functions wrap up the normal values you're dealing with into Decoder Date.Date
contexts so they can be returned.
这篇关于Elm:Json解码器时间戳记至今的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!