Elm: Json decoder timestamp to Date

前端 未结 2 1308
一向
一向 2021-02-19 05:23

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 Strin         


        
2条回答
  •  走了就别回头了
    2021-02-19 06:09

    Two things, a JSON may actually have the milliseconds as an integer, not a string and things have changed since v 0.19 of Elm.

    Given that your JSON looks something like.

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

    Then this would decode to a Time.Posix:

    import Json.Decode as Decode
    
    decodeTime : Decode.Decoder Time.Posix
    decodeTime =
        Decode.int
            |> Decode.andThen
                (\ms ->
                    Decode.succeed <| Time.millisToPosix ms
                )
    

提交回复
热议问题