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

React中如何将API返回的UTC日期字符串格式化为「月份 日期」

解决React中批量格式化UTC日期的问题

首先你代码里有个小错误:map遍历的时候,你用了eventDates.utcStart,但遍历的每一项是data,应该改成data.utcStart,不然所有列表项都会取同一个日期值。

接下来给你两种实用的日期格式化方案,都能把"2022-12-13T06:00Z"转成"December 13"的格式:

方案1:手动原生JS实现

自己定义格式化函数,通过Date对象的UTC方法获取月份和日期,搭配月份数组转换为英文全称:

const formatDate = (dateString) => {
  const date = new Date(dateString);
  const monthNames = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'
  ];
  // 用UTC方法避免时区偏移影响日期计算
  return `${monthNames[date.getUTCMonth()]} ${date.getUTCDate()}`;
};

方案2:用Intl.DateTimeFormat(推荐)

利用浏览器原生的国际化API,代码更简洁,且支持多语言适配:

const formatDate = (dateString) => {
  return new Intl.DateTimeFormat('en-US', {
    month: 'long', // 显示月份全称
    day: 'numeric', // 显示日期数字
    timeZone: 'UTC' // 指定UTC时区,避免本地时区干扰
  }).format(new Date(dateString));
};

修正后的完整代码

把格式化函数和修正后的map逻辑结合,同时记得给列表项加唯一key(React列表渲染的要求):

const eventDates = useRecoilValue(eventDatesState);

const formatDate = (dateString) => {
  return new Intl.DateTimeFormat('en-US', {
    month: 'long',
    day: 'numeric',
    timeZone: 'UTC'
  }).format(new Date(dateString));
};

return (
    <Grid item xs={12}>
        {eventDates.map((data) => (
            <ListItem key={data.id}> {/* 替换成你数据里的唯一标识字段,比如id */}
                <span className="date">{formatDate(data.utcStart)}</span>
            </ListItem>
        ))}
    </Grid>
)

内容的提问来源于stack exchange,提问作者Dirty Bird Design

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:10:48