Skip to content

Commit

Permalink
Merge pull request Expensify#34887 from rezkiy37/feature/28771-get-la…
Browse files Browse the repository at this point in the history
…st-business-day

[No QA] Create helper to get the latest business day of a month
  • Loading branch information
mountiny authored Jan 24, 2024
2 parents 6cfdd6f + 4d857e6 commit a8a3a4c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/libs/DateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ import {
eachDayOfInterval,
eachMonthOfInterval,
endOfDay,
endOfMonth,
endOfWeek,
format,
formatDistanceToNow,
getDate,
getDay,
getDayOfYear,
isAfter,
isBefore,
Expand Down Expand Up @@ -730,6 +733,25 @@ function formatToSupportedTimezone(timezoneInput: Timezone): Timezone {
};
}

/**
* Returns the last business day of given date month
*
* param {Date} inputDate
* returns {number}
*/
function getLastBusinessDayOfMonth(inputDate: Date): number {
let currentDate = endOfMonth(inputDate);
const dayOfWeek = getDay(currentDate);

if (dayOfWeek === 0) {
currentDate = subDays(currentDate, 2);
} else if (dayOfWeek === 6) {
currentDate = subDays(currentDate, 1);
}

return getDate(currentDate);
}

const DateUtils = {
formatToDayOfWeek,
formatToLongDateWithWeekday,
Expand Down Expand Up @@ -774,6 +796,7 @@ const DateUtils = {
getWeekEndsOn,
isTimeAtLeastOneMinuteInFuture,
formatToSupportedTimezone,
getLastBusinessDayOfMonth,
};

export default DateUtils;
31 changes: 31 additions & 0 deletions tests/unit/DateUtilsTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,4 +213,35 @@ describe('DateUtils', () => {
});
});
});

describe('getLastBusinessDayOfMonth', () => {
const scenarios = [
{
// Last business day of May in 2025
inputDate: new Date(2025, 4),
expectedResult: 30,
},
{
// Last business day of February in 2024
inputDate: new Date(2024, 2),
expectedResult: 29,
},
{
// Last business day of January in 2024
inputDate: new Date(2024, 0),
expectedResult: 31,
},
{
// Last business day of September in 2023
inputDate: new Date(2023, 8),
expectedResult: 29,
},
];

test.each(scenarios)('returns a last business day based on the input date', ({inputDate, expectedResult}) => {
const lastBusinessDay = DateUtils.getLastBusinessDayOfMonth(inputDate);

expect(lastBusinessDay).toEqual(expectedResult);
});
});
});

0 comments on commit a8a3a4c

Please sign in to comment.