/*------------------------------------------------------------------------
// This plugin contains some functions for manipulating dates
//
// 27/09/2013 - Sandro Alves Peres
// http://www.zend.com/en/yellow-pages#show-ClientCandidateID=ZEND022656
//-----------------------------------------------------------------------*/
(function($){
$.isLeapYear = function( year )
{
if( (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0) )
{
return true;
}
else
{
return false;
}
};
$.isDate = function( date ) // dd/mm/yyyy
{
if( !/^\d{2}\/\d{2}\/\d{4}$/.test( date ) )
{
return false;
}
var arrDate = date.split("/");
var daysMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var day = parseInt(arrDate[0], 10);
var month = parseInt(arrDate[1], 10);
var year = parseInt(arrDate[2], 10);
if( $.isLeapYear( year ) )
{
daysMonth[1] = 29; // February in Leap Year
}
if( year > 0 )
{
if( month > 0 && month <= 12 )
{
if( day > 0 && day <= daysMonth[ month-1 ] )
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
};
$.daysOfMonth = function( month, year )
{
if( month < 8 && (month % 2) == 1 || month > 7 && (month % 2) == 0 )
{
return 31;
}
if( month != 2 )
{
return 30;
}
if( $.isLeapYear(year) )
{
return 29;
}
return 28;
},
$.addDays = function( date, days ) // days might be negative
{
var arrDate = date.split("/");
var month = parseInt(arrDate[1], 10);
var year = parseInt(arrDate[2], 10);
if( days >= 0 )
{
var day = parseInt(arrDate[0], 10);
day += days;
while( day > $.daysOfMonth(month, year) )
{
day -= $.daysOfMonth(month, year);
month++;
if( month > 12 )
{
month = 1;
year++;
}
}
}
else
{
var day = parseInt(arrDate[0], 10);
for( var i=0; i < (days * -1); i++ )
{
if( day > 1 )
{
day--;
}
else
{
if( month > 1 )
{
month--;
}
else
{
month = 12;
year--;
}
day = $.daysOfMonth(month, year);
}
}
}
for( var i=1; i <= 4; i++ )
{
day = '0' + day;
month = '0' + month;
year = '0' + year;
}
day = day.slice(-2);
month = month.slice(-2);
year = year.slice(-4);
return day.concat("/", month, "/", year);
},
$.toDays = function( date ) // format dd/mm/yyyy
{
var days = 0, days29 = 0;
var date = date.split("/");
var daysMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
date[0] = parseInt(date[0], 10);
date[1] = parseInt(date[1], 10);
date[2] = parseInt(date[2], 10);
for(var i=1; i < date[2]; i++)
{
if( $.isLeapYear(i) )
{
days29++;
}
}
if( $.isLeapYear(date[2]) )
{
if( date[1] > 2 || (date[1] == 2 && date[0] == 29) )
{
daysMonth[1] = 29;
}
}
for( var i=0; i <= (date[1] - 2); i++ )
{
days += daysMonth[i];
}
days += ((date[2] * 365) + date[0] + days29);
return days;
};
$.datediff = function( dateStart, dateEnd )
{
return ($.toDays(dateEnd) - $.toDays(dateStart));
};
})(jQuery);
|