2 回答

TA貢獻1784條經驗 獲得超8個贊
您沒有充分發揮 Luxon 的潛力。您應該將日期保留為 Luxon 對象,使用 Luxon 的方法對其進行所有操作,然后將日期轉換為字符串。
為此,我定義了一個輔助函數prevBusinessDayHelper,該函數采用 Luxon 日期時間并返回表示前一個工作日的日期時間。它完全按照 Luxon 日期時間運行,這很容易。然后在外部函數中,我在 Luxon 日期時間之間進行轉換。
const DateTime = luxon.DateTime;
// use a Set to make lookups cheaper
const federalHolidays = new Set([
'2019-05-27', // <-- you were missing the 0 here in yours
'2019-09-02',
// snip
]);
// recursion is good here because it's very shallow
const prevBusinessDayHelper = dt => {
// use luxon's tools!
const yest = dt.minus({ days: 1 });
if (yest.weekday == 6 || yest.weekday == 7 || federalHolidays.has(yest.toISODate()))
return prevBusinessDayHelper(yest);
return yest;
};
const prevBusinessDay = (isoString, zone) => {
const dt = DateTime.fromISO(isoString).setZone(zone);
return prevBusinessDayHelper(dt).toISODate();
};
console.log(prevBusinessDay("2019-05-28T07:00:00.000Z", "America/New_York"));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>

TA貢獻1840條經驗 獲得超5個贊
當您檢查假期數組時,您正在檢查完整日期而不是日期部分。
function check_previous_business_date(date, timezone) {
const startDate = new Date(luxon.DateTime.fromISO(date).setZone(timezone));
const todayTimeStamp = +new Date(startDate); // Unix timestamp in milliseconds
const oneDayTimeStamp = 1000 * 60 * 60 * 24; // Milliseconds in a day
const diff = todayTimeStamp - oneDayTimeStamp;
const yesterdayDate = new Date(diff);
const yesterdayString = yesterdayDate.getFullYear()
+ '-' + (yesterdayDate.getMonth() + 1) + '-' + yesterdayDate.getDate();
for (startDate.setDate(startDate.getDate() - 1);
!startDate.getDay() || startDate.getDay() === 6 ||
federalHolidays.includes(startDate.toISOString().split('T')[0]) ||
federalHolidays.includes(yesterdayString);
startDate.setDate(startDate.getDate() - 1)
) {
}
return startDate.toISOString().split('T')[0];
}
const federalHolidays= [
'2019-05-27',
'2019-09-02',
'2019-10-14',
'2019-11-11'
];
console.log('Prev. day of 2019-05-28 is ',check_previous_business_date('2019-05-28T07:00:00.000Z', 'America/New_York'));
console.log('Prev. day of 2019-06-20 is ',check_previous_business_date('2019-06-20T07:00:00.000Z', 'America/New_York'));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>
添加回答
舉報