如何用Luxon/Intl API按区域设置获取按周起始日排序的工作日名称
获取按区域设置排序的工作日名称
方法一:基于Luxon调整排序
Luxon内置了获取区域周起始日的方法Info.firstDayOfWeek(),可以用它来重新排列weekdays()返回的数组,让结果符合区域默认的周起始顺序。
const { Info } = luxon; function getLocalizedWeekdays(format = 'short', locale) { const rawWeekdays = Info.weekdays(format, { locale }); const firstDayIndex = Info.firstDayOfWeek({ locale }); // 从起始日分割数组并重新拼接 return [ ...rawWeekdays.slice(firstDayIndex), ...rawWeekdays.slice(0, firstDayIndex) ]; } // 测试德语区域(周一为周起始,结果与原输出一致) console.log(getLocalizedWeekdays('short', 'de')); // ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'] // 测试美式英语区域(周日为周起始,符合预期) console.log(getLocalizedWeekdays('short', 'en-US')); // ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
方法二:原生Intl API实现
如果不想依赖Luxon,直接用浏览器原生的Intl.DateTimeFormat也能实现。通过生成一周的日期并格式化,自动得到符合区域排序的工作日名称。
function getLocalizedWeekdaysIntl(format = 'short', locale) { const formatter = new Intl.DateTimeFormat(locale, { weekday: format }); const weekdays = new Set(); // 以2024-01-07(周日)为起点,生成连续7天的日期 let currentDate = new Date(2024, 0, 7); for (let i = 0; i < 7; i++) { weekdays.add(formatter.format(currentDate)); currentDate.setDate(currentDate.getDate() + 1); } return Array.from(weekdays); } // 测试美式英语区域 console.log(getLocalizedWeekdaysIntl('short', 'en-US')); // ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] // 测试德语区域 console.log(getLocalizedWeekdaysIntl('short', 'de')); // ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']
两种方案各有优势:基于Luxon的方案逻辑更直接,适合已使用Luxon的项目;原生API方案无需额外依赖,适合轻量场景。
内容的提问来源于stack exchange,提问作者kerosene
相关产品推荐
相关产品推荐

