You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中使用react-calendar的formatMonth属性将月份名转为'MMM'格式

React-Calendar 月份名改为'MMM'格式的可运行示例

要将react-calendar的月份名改为MMM格式(如Jan、Feb或中文的1月、2月),可以通过组件提供的格式化属性结合原生API或日期库实现,以下是两种可直接运行的方案:

方案1:使用原生Intl.DateTimeFormat(无需额外依赖)

先确保已安装react-calendar:

npm install react-calendar

组件代码:

import React, { useState } from 'react';
import Calendar from 'react-calendar';
import 'react-calendar/dist/Calendar.css';

const CustomCalendar = () => {
  const [selectedDate, setSelectedDate] = useState(new Date());

  // 自定义月份格式化函数,返回MMM格式
  const formatShortMonth = (date) => {
    // 如需中文格式,将'en-US'改为'zh-CN'
    return new Intl.DateTimeFormat('en-US', { month: 'short' }).format(date);
  };

  return (
    <Calendar
      onChange={setSelectedDate}
      value={selectedDate}
      // 格式化顶部年月显示(如 Jan 2024)
      formatMonthYear={(locale, date) => `${formatShortMonth(date)} ${date.getFullYear()}`}
      // 格式化月份切换按钮等区域的月份名
      formatMonth={formatShortMonth}
    />
  );
};

export default CustomCalendar;

方案2:使用date-fns(适合已有日期库依赖的项目)

先安装依赖:

npm install react-calendar date-fns

组件代码:

import React, { useState } from 'react';
import Calendar from 'react-calendar';
import { format } from 'date-fns';
// 如需中文格式,导入zhCN locale
// import { zhCN } from 'date-fns/locale';
import 'react-calendar/dist/Calendar.css';

const CustomCalendar = () => {
  const [selectedDate, setSelectedDate] = useState(new Date());

  return (
    <Calendar
      onChange={setSelectedDate}
      value={selectedDate}
      formatMonthYear={(locale, date) => 
        // 如需中文,添加{ locale: zhCN }参数
        `${format(date, 'MMM')} ${format(date, 'yyyy')}`
      }
      formatMonth={(date) => format(date, 'MMM')}
    />
  );
};

export default CustomCalendar;

注意事项

  • 确保使用的react-calendar为最新版本,旧版本可能不支持formatMonth、formatMonthYear这些自定义格式化属性。
  • 切换locale可适配不同语言的短月份名,比如中文环境下MMM会显示为1月、2月。

内容的提问来源于stack exchange,提问作者Swee76

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:50:20