Last active
November 3, 2023 08:28
-
-
Save barelyhuman/78750e4845db5e87f6398871e9143011 to your computer and use it in GitHub Desktop.
zoned date-fns-utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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