榆树:Json解码器时间戳到日期

时间:2016-05-10 18:26:26

标签: elm

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

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

stringToDate : Decoder String -> Decoder Date
stringToDate decoder =
  customDecoder decoder Date.fromTime

但它不起作用,因为它返回了一个Result,而不是Date:

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

    Time.Time -> Result String a

But it is:

    Time.Time -> Date.Date

有没有办法进行转换?

2 个答案:

答案 0 :(得分:17)

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

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没有传递任何参数,而不是您尝试传递Decoder String作为参数的示例。解码器的工作方式并不完全。

相反,这可以通过构建更原始的解码器来完成,在这种情况下,我们从解码器string from Json.Decode开始。

然后andThen部分获取解码器给出的字符串值,并尝试将其解析为浮点数。如果它是有效的Float,则会将其输入Date.fromTime,否则就会失败。

failsucceed函数将您正在处理的正常值汇总到Decoder Date.Date个上下文中,以便返回它们。

答案 1 :(得分:1)

两件事,JSON实际上可能以毫秒为整数,而不是字符串,并且自Elm v 0.19起,事情已经发生了变化。

鉴于您的JSON看起来像这样。

{
    ...
    "someTime": 1552483995395,
    ...
}

然后将其解码为Time.Posix:

import Json.Decode as Decode

decodeTime : Decode.Decoder Time.Posix
decodeTime =
    Decode.int
        |> Decode.andThen
            (\ms ->
                Decode.succeed <| Time.millisToPosix ms
            )
相关问题