Skip to content

Instantly share code, notes, and snippets.

@barelyhuman
Last active November 3, 2023 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barelyhuman/78750e4845db5e87f6398871e9143011 to your computer and use it in GitHub Desktop.
Save barelyhuman/78750e4845db5e87f6398871e9143011 to your computer and use it in GitHub Desktop.
zoned date-fns-utils
// import { addDays, subDays } from 'npm:date-fns'; // uncomment for deno
import {addDays,subDays} from "date-fns"
const getCurrentZone = () => Intl?.DateTimeFormat()?.resolvedOptions().timeZone
export function getZonedWeekday(date, zone = getCurrentZone()) {
const weekdayString = new Date(date).toLocaleString('en-GB', {
timeZone: zone,
weekday: 'long',
})
const positional = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
]
const hasIt = positional.findIndex(
x => x.toLowerCase() === weekdayString.toLowerCase()
)
if (hasIt == -1) {
return NaN
}
return hasIt + 1
}
export function addZonedBusinessDays(date, unit, zone = getCurrentZone()) {
const isWeekend = dt => {
const weekday = getZonedWeekday(dt, zone)
return weekday === 6 || weekday === 7
}
let result = addDays(date, unit)
while (isWeekend(result)) {
result = addDays(result, unit)
}
return result
}
export function subZonedBusinessDays(date, unit, zone = getCurrentZone()) {
const isWeekend = dt => {
const weekday = getZonedWeekday(dt, zone)
return weekday === 6 || weekday === 7
}
let result = subDays(date, unit)
while (isWeekend(result)) {
result = subDays(result, unit)
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment