Console.log is your friend

Although it only works in Chrome and FireBug, I’ve found console.log() to be an extremely handy tool for debugging javascript without having to step through code.

Here’s a bit of code I’ve found handy to make sure browsers without console.log don’t bomb out in case you forget to take your console.log statements out:

if (window.console == undefined) { window.console = {log:function(){},dir:function(){}}; }

Make sure to add this near the top of your scripts and you’ll be able to use console.log without fear of it causing problems in browsers like IE.

[]

How many Mondays are in the month of…

I recently ran into a situation where I needed to know how many Monday’s were in a given month via javascript and figured I would make the function (which depends on Date extensions by ExtJS) for it available here in case anyone else runs into the same problem.

/*
 * This function takes a date and determines how many of each day of the week
 * are in the month.
 */
var getMonthlyDayOfWeekCount = function(sourceDate){
    var iDate = Date.parseDate(sourceDate.format('m') + '/1/' + sourceDate.format('Y'), 'm/j/Y');
    var days = [0, 0, 0, 0, 0, 0, 0];

    while (iDate.format('m') == sourceDate.format('m')) {
        days[iDate.format('w')]++;
        iDate = iDate.add(Date.DAY, 1);
    }

    return days;
};

/*
 * This function takes a date and returns an interger cotnaining the
 * occurance of this day in the month.
 *
 * Useful for when you want to know if this is the 1st or 3rd Saturday in
 * the month.
 */
var getDayInMonthCount = function(sourceDate){
    var iDate = Date.parseDate(sourceDate.format('m') + '/1/' + sourceDate.format('Y'), 'm/j/Y');
    count = 1;

    while (iDate.format('m') == sourceDate.format('m')) {
        if (iDate.format('z Y') == sourceDate.format('z Y')) {
            return count;
        }

        if (iDate.format('w') == sourceDate.format('w')) {
            count++;
        }
        iDate = iDate.add(Date.DAY, 1);
    }

    return count;
};
[]