Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix addBusinessDays when input date is a weekend day (#1628) #1790

Merged
merged 1 commit into from Jul 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/addBusinessDays/index.js
Expand Up @@ -2,6 +2,8 @@ import isWeekend from '../isWeekend/index.js'
import toDate from '../toDate/index.js'
import toInteger from '../_lib/toInteger/index.js'
import requiredArgs from '../_lib/requiredArgs/index.js'
import isSunday from '../isSunday/index.js'
import isSaturday from '../isSaturday/index.js'

/**
* @name addBusinessDays
Expand All @@ -25,6 +27,7 @@ export default function addBusinessDays(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments)

const date = toDate(dirtyDate)
const startedOnWeekend = isWeekend(date)
const amount = toInteger(dirtyAmount)

if (isNaN(amount)) return new Date(NaN)
Expand All @@ -44,6 +47,16 @@ export default function addBusinessDays(dirtyDate, dirtyAmount) {
if (!isWeekend(date)) restDays -= 1
}

// If the date is a weekend day and we reduce a dividable of
// 5 from it, we land on a weekend date.
// To counter this, we add days accordingly to land on the next business day
if (startedOnWeekend && isWeekend(date) && amount !== 0) {
// If we're reducing days, we want to add days until we land on a weekday
// If we're adding days we want to reduce days until we land on a weekday
if (isSaturday(date)) date.setDate(date.getDate() + (sign < 0 ? 2 : -1))
if (isSunday(date)) date.setDate(date.getDate() + (sign < 0 ? 1 : -2))
}

// Restore hours to avoid DST lag
date.setHours(hours)

Expand Down
7 changes: 7 additions & 0 deletions src/addBusinessDays/test.js
Expand Up @@ -81,4 +81,11 @@ describe('addBusinessDays', function() {
assert.throws(addBusinessDays.bind(null), TypeError)
assert.throws(addBusinessDays.bind(null, 1), TypeError)
})
it('starting from a weekend day should land on a weekday when reducing a divisible by 5', function() {
const substractResult = addBusinessDays(new Date(2019, 7, 18), -5)
assert.deepEqual(substractResult, new Date(2019, 7, 12))

const addResult = addBusinessDays(new Date(2019, 7, 18), 5)
assert.deepEqual(addResult, new Date(2019, 7, 23))
})
})