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

React/TypeScript项目如何将API返回的日期格式化为「22 June 2021」样式

方案1:原生JavaScript实现(无第三方依赖)

直接使用浏览器内置的Intl.DateTimeFormatAPI即可实现需求,TypeScript天然支持该API的类型定义,无需额外配置:

// 封装通用格式化函数
const formatApiDate = (isoTimeStr: string): string => {
  const date = new Date(isoTimeStr);
  return new Intl.DateTimeFormat('en-GB', {
    day: 'numeric',
    month: 'long',
    year: 'numeric'
  }).format(date);
}

在组件模板中替换原有绑定即可:

{/* 原写法 */}
{/* {data.time} */}
{/* 新写法 */}
{formatApiDate(data.time)}

注:en-GB locale 会输出「日期 月份全称 年份」的结构,刚好匹配你需要的22 June 2021格式,所有现代浏览器均支持该API,仅兼容IE10及以下版本时才需要考虑其他方案。

方案2:第三方库实现(适合复杂日期处理场景)

如果项目本身有大量日期计算、格式化需求,推荐使用轻量化的date-fns库(已停止维护的moment.js不推荐使用):

  • 安装依赖:
npm install date-fns
  • 组件内直接使用:
import { format } from 'date-fns';
import { enGB } from 'date-fns/locale';

// 模板中调用
{format(new Date(data.time), 'dd MMMM yyyy', { locale: enGB })}

注:格式符dd代表两位日期,MMMM代表月份全称,yyyy代表四位年份,可根据需求灵活调整格式规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:18:00