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)..
How do we fix this?
There are 2 parts to the answer:
- 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”).
- Ensure the string we are passing into the Date() object is in an allowed format (best format is ISO: yyyy-mm-dd).
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.
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.