JavaScript Date Tips

The other night at the Hudson Software Craftsmanship meeting at the Falafel Software training center in Hudson, Ohio, I did the Red Pencil Kata using JavaScript. Although I’ve run into it in the past, I was stuck for a little while (I was the odd man out without a pairing partner to help find these things faster) due to one of JavaScript’s “fun” date conventions. Being a C# developer primarily, there are many small things I have to remember that are different between JavaScript and C# (like where to declare variables, for instance). In this case, it was the code for generating a particular date that bit me. At one point, I wanted to generate a date that was over 30 days in the past (relative to the current date, which was 16 July 2014), so I wrote this:

var day1 = new Date(2014, 6, 14); // javascript

If I were in C#, this code would have worked fine:

var day1 = new DateTime(2014, 7, 11); // C#

You see, the folks who wrote C# were not insane, and so they didn’t arbitrarily make the middle ‘month’ parameter 0-based, like the JavaScript folks did. In my kata, it was important that certain things happen around the 30-day window, and of course my silly mistake had created a date that was only 3 days in the past, not 32. Oops. Of course, you should be able to avoid this by using a string, right? That’s what some of my fellow developers suggested. What do you suppose this yields?

var day1 = new Date(“2014-07-01”); // javascript

If you answered 30 June 2014, you’re right! Of course, that’s just what you would expect, too. WAT?

Of course, if you use something hideous like this, it works correctly (in the United States, which expects M/D/Y format):

var day1 = new Date(“7/14/14”); // javascript

This, too, will give you what you expect, though it’s a bit verbose:

var day1 = new Date(“July 14, 2014”); // javascript

Go ahead and play with these options yourself here:

function log(x)
{
    $("#output").append(x + '
');
}

(function () {
    var day1 = new Date(2014, 6, 14);
    log("day1: " + day1.toDateString());
    var day2 = new Date(2014, 0, 1);
    log("day2: " + day2.toDateString());
    var day3 = new Date("2014-07-01");
    log("day3: " + day3.toDateString());
    var day4 = new Date("7/14/14");
    log("day4: " + day4.toDateString());
})();

ardalis.com

Leave a Reply

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