How to get first, second, third, fourth and last day date in javascript

I have created a function which is use to get date by the day and position in javascript. Actually my requirenment is when i passed day and its position then i got the date. To fullfil my requirenment i just created a function below.

For Example : Suppose if you want the second friday or last sunday or any thing else . You just need to pass the position and day then you get the corresponding date. 

function searchDayByPosition(searchday, searchposition){
var currentdate = new Date();
var currentmonth = currentdate.getMonth();
var currentyear = currentdate.getFullYear();
var lastDateOfMonth = new Date(currentyear, currentmonth+1, 0).getDate();
var searcharr = [];
for(var i=1;i<=lastDateOfMonth;i++) {
var day = new Date(currentyear, currentmonth, i).getDay();
if(day==searchday){
searcharr.push(i);
}
if(i==lastDateOfMonth){
if(searchposition!=5){
return searcharr[searchposition-1];
}else{
return searcharr[searcharr.length-1];
}
}
}

}


Description of function:
-----------------------------

1-- Sunday is 0, Monday is 1 .... and Saturday is 6 

2-- First denotes 1 , Second denotes 2 .... and Last denotes 5

3-- If you want the first sunday then you have to pass value like this searchDayByPosition(0, 1)

4-- If you want the last friday then you have to pass value like this searchDayByPosition(5, 5).

If you have any question related to this function comment below textbox i will reply you back.

Chears 
Happy coding :)



Post a Comment

Previous Post Next Post