New Version of DP_DateExtensions and Some Esoteric Integer Parsing

[Actually the “new” version is nearly a month old at this point but I forgot to do an entry to announce it.]

There’s a new version of my JavaScript date extensions, DP_DateExtensions, available.  This release fixes a significant, but interesting bug brought to my attention by Kevin Warnke.  He noticed that, sometimes, when you parsed a date with a 12-hour clock the resulting time was simply wrong – often off by weeks.  This, for some reason, annoyed him.

After digging I did find (and fix) the problem.  As you might expect to parse a time with a 12-hour time you need to take the time given and add 12 to it (if “PM”) to convert it to a 24-hour clock.  To do this I did some simple addition:

Hours = Hours + 12;

This worked fine in most cases.  However if “Hours” had leading zero, like “04” JavaScript treats this as a string and would result in “0412” rather than “16” as you might expect.  However when adding the value to a date JavaScript happily treats it as a number – so instead of adding 16 hours to my new date this resulted in adding 412 hours – or over 17 extra days!

Although there are many ways to fix this I decided to force the conversion by using the parseInt() function like so (the “10” indicates that you want to parse the value as base 10):

Hours = parseInt(Hours, 10) + 12;

This fixed the problem nicely.  In the end, a pretty silly error that I should have caught much sooner.

Leave a Reply © 2014 Frontier Theme