Working with JavaScript dates deserialized from JSON

This is a quick post inspired by a problem I helped a colleague with yesterday.

The problem is a “date.getFullYear is not a function” error was thrown when calling getFullYear() on a TypeScript Date object.

This was happening when the Date object was populated from a deserialized JSON string and the deserialization was silently failing in the background in the app.

It happens due to the format of the date string, and on top of that, the string is in the format “dd/mm/yyyy” (the short date format used by most of the world)..
JavaScript being what it is, it doesn’t like this for dates like “18/05/2018” (18th May) because it actually wants to do a conversion on “05/18/2018” (US short date format).
More importantly, you can’t implicitly deserialize a string representation of a date to a JavaScript Date object. How does the dezerializer (in this case JSON.parase()) know the string is really a date?

How do we fix this?

There are 2 parts to the answer:

  1. We need to explicitly set the target/deserialized date variable/field to a Date()
    i.e. myObject.myDate = new Date(“date-string-in-accepted format”);
    For example: myObject.myDate = new Date(“05/18/2018”).
  2. Ensure the string we are passing into the Date() object is in an allowed format (best format is ISO: yyyy-mm-dd).
    For example:
    myObject.myDate = new Date(“2018-05-18”) – using ISO date format.
    myObject.myDate = new Date(“05/18/2018”) – using US date format.

Below you can see it a quick running code sample I whipped up to demonstrate this.

Play around with commenting.uncommenting the “json = “…”;” lines and the “let dataObject: DataObject = JSON.parse(json);” line.

Running Example

NOTE: You can pop the editor open in a new window by selecting “Edit On StackBlitz” in the bottom-left of the inserted window.
Select the folded-page icon at the top of the left column (below the StackBlizt blue/white icon) to see the list of files.

If you’re using Internet Explorer or there’s just a black window below, here’s the link to the code (and I suggest using a “modern” browser – Chrome and Edge both work): https://stackblitz.com/edit/typescript-riapny.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.