Roll-your-own date parser in Javascript – please don’t!

 I was debugging some code the other day where there was a problem with the date being set incorrectly. A date picker was used in the GUI to set a date that was sent to the server. For some reason, when a date in September was picked, the date saved in the database ended up being in December! Well, it turns out that since the date format was using leading zeroes, and Javascript has this magic feature (apparently deprecated, but still in use) where if the number passed to the parseInt function starts with 0 it is interpreted as an octal value! Now this works fine with values from 01 – 07 (since they are the same anyway), but obviously not with 08 and 09. If the function had been used previously we might have spotted the pattern, but it was only starting to be used now.

Morale of the story? Don’t reinvent the wheel, there are many good already existing javascript date parsers: Moment.js, Datejs or as a part of ExtJS (if you’re already using that) or as a a JQuery plugin (if you’re using that). Secondly; using an IDE with proper Javascript support with quick documentation lookup might have helped spotting the problem in the first place.

At last, if you really, really,  have no option but to roll your own, then please test it with all (possible or feasible) permutations!


2 kommentarer om “Roll-your-own date parser in Javascript – please don’t!

  1. Sett på makan, aktivitet på Birgers Blogg!

    Mett av JS-funksjonalitet i IntelliJ, så om du ikke bruker det enda, ta steget. Koster noen kroner, men de er fort innspart igjen sammenlignet med hvor mye tid man bruker på å kuke rundt i feks Eclipse.

    1. Jepp, hvem skulle tro det! Bruker IntelliJ, og det er absolutt verdt kronene bare for JS-støtten i seg selv (og mtp. hvor mye jeg ser Eclipse-brukere «sloss» med GUI’et sitt – nesten verdt en rant i seg selv).

Legg igjen en kommentar

Fyll inn i feltene under, eller klikk på et ikon for å logge inn:

Du kommenterer med bruk av din konto. Logg ut /  Endre )


Du kommenterer med bruk av din Facebook konto. Logg ut /  Endre )

Kobler til %s