如何在DayJS中获取仅含月份与年份的本地化格式?
DayJS实现本地化年月显示方案
DayJS确实没有直接提供仅包含年月的本地化预设格式,不过可以通过两种方式实现需求:
方法一:动态提取本地化格式组合
利用DayJS的localeData()方法获取当前语言环境的配置,从已有格式(比如LL)中判断年月的排列顺序,再拼接成目标格式。
// 自定义格式化函数 function formatMonthYear(date) { const localeData = date.localeData(); // 获取本地化的月份全称和四位年份 const fullMonth = localeData.format(date, 'MMMM'); const fullYear = localeData.format(date, 'YYYY'); // 从LL格式中判断年月的排列优先级 const llFormatPattern = localeData.formatLong('LL'); if (llFormatPattern.includes('MMMM') && llFormatPattern.includes('YYYY')) { // 月份在年份前则返回「月 年」,反之返回「年 月」 return llFormatPattern.indexOf('MMMM') < llFormatPattern.indexOf('YYYY') ? `${fullMonth} ${fullYear}` : `${fullYear} ${fullMonth}`; } // 兜底默认格式 return `${fullMonth} ${fullYear}`; } // 示例使用 import dayjs from 'dayjs'; import 'dayjs/locale/zh-cn'; import 'dayjs/locale/en'; // 英文环境 console.log(formatMonthYear(dayjs().locale('en'))); // 输出:December 2022 // 中文环境 console.log(formatMonthYear(dayjs().locale('zh-cn'))); // 输出:2022 十二月
方法二:扩展本地化格式配置
给需要的语言环境添加自定义的年月格式,之后可以直接用format()方法调用,更贴合DayJS的原生用法。
import dayjs from 'dayjs'; import en from 'dayjs/locale/en'; import zhCN from 'dayjs/locale/zh-cn'; // 扩展英文locale的自定义格式「MY」 en.formatLong.MY = 'MMMM YYYY'; dayjs.locale(en, null, true); // 持久化修改英文配置 // 扩展中文locale的自定义格式「MY」 zhCN.formatLong.MY = 'YYYY年MMMM'; dayjs.locale(zhCN, null, true); // 持久化修改中文配置 // 使用示例 dayjs().locale('en').format('MY'); // December 2022 dayjs().locale('zh-cn').format('MY'); // 2022年十二月
两种方案对比:
- 方法一无需修改locale配置,动态适配所有已加载的语言环境,适合多语言频繁切换的场景;
- 方法二配置后调用更简洁,格式可以完全自定义,适合固定使用几种语言的场景。
内容的提问来源于stack exchange,提问作者Proz1g
相关产品推荐
相关产品推荐

