Reputation: 182
This is my code
const date = new Date();
const startDate = new Date(date.getFullYear(), date.getMonth(), 1);
const endDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);
const getDateArray = function(start, end) {
const arr = [];
const dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
const dateArr = getDateArray(startDate, endDate);
in this above code I got the current month date list dateArr
, Now I need to group the days by a week, from the week list I need to filter only week start date and weekend date that must be in list formate I tried with the above code but I cant proceed to next.
Upvotes: 0
Views: 229
Reputation: 8751
This works.
var date = new Date();
console.log("All Weeks : ", getWeeksInaMonth())
console.log("Current Week : ", getCurrentWeek())
console.log("Current and previous weeks : ",getCurrAndPrevWeeks())
function getFormattedDate(dateobj)
{
var date = dateobj.getDate(), month = dateobj.getMonth()+1, year = dateobj.getFullYear();
var formattddate = (date<10?"0":"")+date+"/"+(month<10?"0":"")+month+"/"+year;
return formattddate;
}
function getWeeksInaMonth()
{
var startdate = new Date(date.getFullYear(), date.getMonth(), 1);
var enddate = new Date(date.getFullYear(), date.getMonth()+1, 0);
var weeks = [];
for(var i=1,n=enddate.getDate();i<n;)
{
startdate.setDate(i);
var arr = [getFormattedDate(startdate)];
i =i+ 6-startdate.getDay();
if(i>n) i=i-(i-n);
startdate.setDate(i);
arr.push(getFormattedDate(startdate));
i++;
weeks.push(arr);
}
return weeks
}
function getCurrentWeek()
{
var today = new Date(), day = today.getDay();
return [getFormattedDate(new Date(today.getFullYear(),today.getMonth(),today.getDate()-day)),
getFormattedDate(new Date(today.getFullYear(),today.getMonth(),today.getDate()+6-day))];
}
function getCurrAndPrevWeeks()
{
var startdate = new Date(date.getFullYear(), date.getMonth(), 1);
var enddate = new Date(date.getFullYear(), date.getMonth()+1, 0);
var today = new Date().getDate();
var weeks = [];
for(var i=1,n=enddate.getDate();i<n;)
{
startdate.setDate(i);
var arr = [getFormattedDate(startdate)];
i =i+ 6-startdate.getDay();
if(i>n) i=i-(i-n);
startdate.setDate(i);
arr.push(getFormattedDate(startdate));
weeks.push(arr);
if(today>=i-6 && today<=i) break;
i++;
}
return weeks;
}
Upvotes: 1