Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Reda-ELOUAHABI/af86949cf8991431afa0c89e7a680964 to your computer and use it in GitHub Desktop.
Save Reda-ELOUAHABI/af86949cf8991431afa0c89e7a680964 to your computer and use it in GitHub Desktop.
Javascript (Node.js) function for getting last working/business day of the month.
/**
* Finds last working/business day of the month.
*
* Not tested for cross-browser compability. Works in Node.js though.
*
* EXAMPLES:
*
* 1. Returns last day of the last month of the current year:
*
* var result = lastBusinessDayOfMonth();
*
* 2. Returns last day of the current month of the current year:
*
* var date = new Date();
* var year = date.getFullYear();
* var month = date.getMonth() + 1;
*
* if (12 === month) {
* month = 0;
* year++;
* }
*
* var result = lastBusinessDayOfMonth(year, month);
*
* @param year Provide null for current year, provide xxxx for custom year.
* @param month Provide null for current month, provide 0-11 for custom month.
*
* @returns object Date A resulting date object of the last working/business day of the month.
*/
function lastBusinessDayOfMonth(year, month) {
var date = new Date();
var offset = 0;
var result = null;
if ('undefined' === typeof year || null === year) {
year = date.getFullYear();
}
if ('undefined' === typeof month || null === month) {
month = date.getMonth();
}
do {
result = new Date(year, month, offset);
offset--;
} while (0 === result.getDay() || 6 === result.getDay());
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment