How can I create a function for finding the number of business days (weekdays) of the current month? Can you code in simple JavaScript without jQuery?
function daysInMonth(iMonth, iYear)
{
return 32 - new Date(iYear, iMonth, 32).getDate();
}
function Detail()
{
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var dim = daysInMonth(month, year);
alert(dim);
}
function Businessday(iMonth, iYear)
{
// Enter code here
}
function isBusinessDay()
{
var d = new Date();
var day = d.getDay();
switch(day) {
case 0:
document.write("Today is weekend");
break;
case 6:
document.write("Today is weekend");
break;
default:
document.write("Today is a business day");
}
}
OK, let’s solve this one piece at a time.
The Date object in JavaScript has a method, getDay. This will return 0 for Sunday, 1 for Monday, 2 for Tuesday, … 6 for Saturday. Given that, we can conclude that we want to not count days whose
getDayreturns 0 or 6.You already have a function to return the number of days in a month, so assuming that, we can loop over all of the days and check the result of getDay.
daysInMonthmakes the assumption that the month is zero-based; so 0 = January.I’d encourage you to try solving this on your own from here; otherwise read on.
Let’s start with an
isWeekdayfunction. We need the year, month, and day:We do exactly as we talked about above: we construct a Date, and use
getDayto determine if it’s a day.Now we need to loop over all of the days in the month:
We loop over all of the days in the month. We add 1 when checking
isWeekdaybecause the day, unlike month, is 1 based. If it is, we incrementweekdays, then return.So we can use
getWeekdaysInMonthlike this:Which will result in 21.