Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In


    Decode JSON Dates into Elm

    Enrico BuonannoEnrico Buonanno

    Dates are not a primitive type in JSON, so they need to be decoded as strings with special formatting. Fortunately, json-extra has a convenience date decoder, meaning you don't have to think about these details too much.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    Instructor: 00:01 how does it work with dates? For example, let's assume that our user object has a date of birth field. Let me add a valid date for this field. How could you decode this? Let's start with adding this to our model. We need to import date. In our user type alias, we have date of birth of type date. Then, we need to update our user decoder, we have another field.

    00:40 We can use a decoder called date. That is exposed in json.decoder.extra. Let me save that. I forgot to change this to map six, because now, we have one more field. Other than that, it works fine, and you see our date has been populated. It's important to notice that date is a decoder in Json.Decoder.Extra and not in Json.Decode. That's because date is not a JSON primitive, but rather, dates in JSON are specially-formatted strings.

    01:13 If you wanted to know more about how this date decoder works, it essentially parses as a string. Then, it uses the date from string function. This returns a result. We then need to compose this with from result to get a decoder. If I were to import from result, there you see that this works just the same. Of course, simply using date is the simplest and most readable solution...