React v5版FullCalendar在Firefox、Safari浏览器意大利语本地化失效问题
你遇到的问题是Firefox、Safari的Intl API会优先继承页面根元素的lang属性设置,优先级高于你传入toLocaleDateString的语言参数,同时FullCalendar v5默认会调用原生Intl API做日期格式化,才会出现其他界面元素正常、仅月份日期显示英文的情况,可按以下步骤解决:
- 先修正页面根语言配置
打开控制台执行document.documentElement.lang,如果返回值为en/en-US,在你的React应用入口文件中添加如下代码修改页面根元素语言:
document.documentElement.lang = 'it'
修改后刷新页面测试,大部分情况下这个配置就能解决问题。
- 如果上述配置不生效,手动覆盖FullCalendar的日期格式化逻辑,强制使用自带的意大利语文本,不走原生Intl API:
首先替换全量语言包引入为单独的意大利语包:
import itLocale from '@fullcalendar/core/locales/it'
然后修改FullCalendar组件的配置:
<FullCalendar plugins={[dayGridPlugin, interactionPlugin, timeGrid, bootstrapPlugin]} headerToolbar={{ left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridWeek,timeGridDay' }} weekends={true} themeSystem="bootstrap" // 直接传入意大利语包对象,无需配置locales属性 locale={itLocale} initialView="dayGridMonth" selectable={true} editable={true} // 新增日期格式覆盖配置 titleFormat: { year: 'numeric', month: 'long' }, dayHeaderFormat: { weekday: 'long' }, eventTimeFormat: { hour: '2-digit', minute: '2-digit', hour12: false }, // 自定义日期格式化方法,直接调用本地化包内置文本 localeUtils: { formatDate: (date, options, locale) => { if (options.weekday === 'long' && options.month === 'long' && options.day === 'numeric' && options.year === 'numeric') { return `${locale.weekdays.long[date.getDay()]} ${date.getDate()} ${locale.months.long[date.getMonth()]} ${date.getFullYear()}` } if (options.month === 'long' && options.year === 'numeric') { return `${locale.months.long[date.getMonth()]} ${date.getFullYear()}` } if (options.weekday === 'long') { return locale.weekdays.long[date.getDay()] } return date.toLocaleDateString('it-IT', options) } } />
这个方案完全绕过了浏览器原生Intl API的差异,在所有浏览器下都能稳定显示意大利语的日期和月份。
内容的提问来源于stack exchange,提问作者Luca Gentile
相关产品推荐
相关产品推荐

