JavaScript DateDiff Functions

Here's some JavaScript functions that I use like VB's DateDiff function. I've seen some other functions but most take the number of days and end up close but not quite. They also don't correctly handle leap years.

DateDiffYears will return the number of years between two dates while DateDiffMonths will return the number of months. Couple of things to remember. DateDiffYears is often used to determine age so it won't go negative but will return zero. Thus, if the end date precedes the start date you'll get zero as the result. Also, pass start and end as date objects rather than strings. LAstly, you need DateDiffYears to use DateDiffMonths.

// Calcuates the number of years between two dates.
// start - a date object that defines the beginning of the range
// end - a date object that defines the end of the range
function DateDiffYears(start, end)
{
    var years = end.getFullYear() - start.getFullYear();
    var month1 = start.getMonth()
    var month2 = end.getMonth()
    var day1 = start.getDate()
    var day2 = end.getDate()
    if (month2 < month1)
        {
            years -= 1;
        }
    else
        {
            if (month2 = month1)
                {
                    if (day2 < day1)
                        {years -= 1;}
                }
        };
    
    if (years < 0)
        {years=0;}
        
    return years;
}

// Calcuates the number of months between two dates.
// start - a date object that defines the beginning of the range
// end - a date object that defines the end of the range
function DateDiffMonths(start, end)
{
    var years1 = DateDiffYears(start, end);
    var years2 = end.getFullYear() - start.getFullYear();
    var months = years1 * 12
    var month1 = start.getMonth()
    var month2 = end.getMonth()
    var day1 = start.getDate()
    var day2 = end.getDate()
    if (years1 != years2)
        {
            months = months + 11 - (month1 - month2);
        }
    else
        {
            months = months + (month2 - month1);
            if (day2 < day1)
                        {months -= 1;}
        };
        
    return months;
}

Someday I will combine them into one DateDiff function but that's a later entry.

Technorati Tags: ,,

Comments

Popular posts from this blog

Migrating Legacy Apps to the New SimpleMembership Provider

Windows 8 Keyboard Shortcuts

Get Asp.Net Profile properties from Sql