Luxon JS如何根据星期数字编号获取对应星期名称
Luxon 星期数字转名称实现方案
Luxon 中星期数值采用1-7的规则(1为周一,7为周日),可以通过set方法指定weekday属性,再配合toFormat方法输出对应格式的星期名称,和Moment的实现逻辑基本一致,仅需做一次数值适配即可。
基础用法(直接使用Luxon 1-7原生数值)
import { DateTime } from 'luxon'; // 输出英文最短星期名,对应Moment示例中`ddddd`的输出效果 DateTime.local().set({ weekday: 7 }).toFormat('ccccc'); // S // 输出中文完整星期名 DateTime.local().set({ weekday: 7 }).setLocale('zh-CN').toFormat('cccc'); // 星期日
适配Moment 0-6数值的封装
如果你的项目中现有数值是Moment风格的0-6规则(0为周日,6为周六),可以做一层简单的数值转换再调用:
import { DateTime } from 'luxon'; /** * 根据Moment风格的星期数字获取对应星期名称 * @param {number} momentWeekday - 0-6范围的星期数值,0为周日 * @param {string} locale - 区域语言,默认zh-CN * @param {string} format - 输出格式,默认cccc(完整名称) * @returns {string} 星期名称 */ function getWeekdayName(momentWeekday, locale = 'zh-CN', format = 'cccc') { const luxonWeekday = momentWeekday === 0 ? 7 : momentWeekday; return DateTime.local() .set({ weekday: luxonWeekday }) .setLocale(locale) .toFormat(format); } // 测试用例 getWeekdayName(0); // 星期日 getWeekdayName(1); // 星期一 getWeekdayName(0, 'zh-CN', 'ccc'); // 周日 getWeekdayName(0, 'zh-CN', 'ccccc'); // 日
常用星期格式化令牌参考
ccccc:最短标识,中文下为单字,如「日」「一」ccc:短名称,中文下为两字,如「周日」「周一」cccc:完整名称,中文下为三字,如「星期日」「星期一」
内容的提问来源于stack exchange,提问作者Rain Man
相关产品推荐
相关产品推荐

