Tuesday, January 20, 2009

Start date and End date of a week

Javascript function to to get the starting date and end date of a week by giving the week number (1 to 5), Month number (1 to 12), valid year as parameter:

function GetWeekStartEndDate(){
var week = 5;
var month = 2;
var year = 2002;

var PositiveOneDay = new Date(new Date('1/2/2000') - new Date('1/1/2000'));
var NegetiveOneDay = new Date(new Date('1/1/2000') - new Date('1/2/2000'));
var dt , stDate , endDate
//Get first day of month
dt = new Date(month + '/1/' + year);
//Seek to intended week
var i = 1;
for(i = 1 ; i < (week-1)*7 ; i++){
dt = new Date(dt - NegetiveOneDay);
}
//if found date is week end get immediate next week start date
while (dt.getDay() == 0 || dt.getDay() == 6){
dt = new Date(dt - NegetiveOneDay);
}
//if found date is in next month then invalid input
if (dt.getMonth() == month - 1){
stDate = dt;
endDate = dt;
//Seek to week start date
while (stDate.getDay() != 1)
{
stDate = new Date(stDate - PositiveOneDay);
}
//Seek to week end date
while (endDate.getDay() != 5)
{
endDate = new Date(endDate - NegetiveOneDay);
}

alert('Starting date of a week : ' + stDate.toString());
alert('Ending date of a week : ' + endDate.toString());
}
else{
alert('Invalid Input');
}
}


No comments:

Post a Comment