A Date With a Parser

Remy escaped the enterprise world and now makes LEDs blink pretty. Editor-in-Chief for TDWTF.

PastorGL inherited some front-end code. This front-end code only talks to a single, in-house developed back-end. Unfortunately, that single backend wasn’t developed with any sort of consistency in mind. So, for example, depending on the end-point, sometimes you need to pass fields back and forth as productID, sometimes it’s id, productId, or even _id.

Annoying, but even worse is dealing with the dreaded date datatype. JSON, of course, doesn’t have a concept of date datatypes, which leaves the web-service developer needing to make a choice about how to pass the date back. As a Unix timestamp? As a string? What kind of string? With no consistency on their web-service design, the date could be passed back and forth in a number of formats.

Now, if you’re familiar with the JavaScript Date datatype, you’d know that it can take most date formats as an input and convert them into a Date object, which gives you all the lovely convenience methods you might need. So, if for example, you wanted to convert a date string into a Unix timestamp, you might do something like this:

That would cover 99% of cases, but PastorGL’s co-worker didn’t want to cover just those cases, and they certainly didn’t want to try and build any sort of consistency into the web service. Not only that, since they knew that the web service was inconsistent, they even protected against date formats that it doesn’t currently send back, just in case it starts doing so in the future. This is their solution: