Wednesday, March 24, 2010

Date Comparer in Javascript

This code is used to comapre date and sort dates.


function DateComparer(firstValue, SecondValue)
{
    var sortFirstRow  = GetFormattedDateForSort(firstValue);
    var sortSecondRow = GetFormattedDateForSort(SecondValue);
    
    if(sortFirstRow == sortSecondRow) return 0;
    if(sortFirstRow >  sortSecondRow) return 1;
    if(sortFirstRow <  sortSecondRow) return -1;
}
function GetFormattedDateForSort(value)
{
   var retValue = "";
   if(value != "")
   {
        var month   = value.split('/')[0];
        var day     = value.split('/')[1];
        var year    = value.split('/')[2];
        
        if(month != undefined)
        {
            if(month.length == 1 && month < 10)
            {
                month = '0' + month;
            }
        }
        if(day != undefined)
        {
            if(day.length == 1 && day < 10)
            {
                day = '0' + day;
            }
        }
        
        retValue = year + month + day ;
    }
    return retValue;
}