Reputation: 468
I'm trying to make a program in angular where employees can mark their work hours. But I can't figure out how to get all the workdates into an array. I tried this
getDaysInMonth(month, year) {
this.date = new Date(Date.UTC(year, month,));
this.days = [];
while (this.date.getMonth() === month) {
if(this.date.getDay() == 6 || this.date.getDay() == 0) {
return "weekend";
}
this.days.push(new Date(this.date));
this.date.setDate(this.date.getDate() + 1);
}
return this.days;
}
Upvotes: 0
Views: 1636
Reputation: 2465
This is a code I have developed in one of my projects, hope it solves your problem:
export function findWorkingDays(startDate: Date, endDate: Date): number {
startDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
endDate = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
let days = 0;
const curDate = startDate;
while (curDate <= endDate) {
const dayOfWeek = curDate.getDay();
if (!((dayOfWeek === 6) || (dayOfWeek === 0))) {
days++;
}
curDate.setDate(curDate.getDate() + 1);
}
return days;
}
findWorkingDays(new Date("01.10.2019"), new Date("31.10.2019"));
Upvotes: 0
Reputation: 874
The problem is that you return "weekend" from your if, which means that once you hit a weekend day, you will exit the function, return "weekend" and won't keep checking the other days. here is a fixed snippet:
getDaysInMonth(month, year) {
this.date = new Date(Date.UTC(year, month,));
this.days = [];
while (this.date.getMonth() === month) {
this.date.setDate(this.date.getDate() + 1);
if(this.date.getDay() == 6 || this.date.getDay() == 0)
continue;
this.days.push(new Date(this.date));
}
return this.days;
}
Upvotes: 2
Reputation: 21
The below code will give you dates of working days of a given month and year.
function getWorkingDays(startDate, endDate){
var workingDates = [];
var currentDate = startDate;
while (currentDate <= endDate) {
var weekDay = currentDate.getDay();
if(weekDay != 0 && weekDay != 6){
workingDates.push(currentDate.getDate());
}
currentDate.setDate(currentDate.getDate()+1);
}
return workingDates;
}
function getDaysInMonth(month, year) {
var begin = new Date(month + '/01/' + year);
var end = new Date(begin.getFullYear(), begin.getMonth() + 1, 0);
console.log(getWorkingDays(begin, end));
}
getDaysInMonth(11, 2019);
Upvotes: 1
Reputation: 1251
Your return
stop the continuity of your while
and your method, simply replace it by a continue;
to stop the continuity of the current iteration of your while and to skip to the next one.
Upvotes: 0