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

如何用JavaScript/ES6/ReactJS将API返回的ISO日期转为April 1, 2018格式

嘿,这个日期格式转换的需求太常见啦!我给你整理了几种在JavaScript/ES6和React里的实现方式,都是实用又靠谱的~

方法一:使用原生Intl.DateTimeFormat(首推)

这是现代浏览器原生支持的API,不仅代码简洁,还能很好地处理本地化,完全不需要引入第三方库。直接指定en-US locale就能得到你想要的April 1, 2018格式:

const formatDate = (isoDate) => {
  // 先把ISO字符串转成Date对象
  const date = new Date(isoDate);
  
  // 用Intl API格式化
  return new Intl.DateTimeFormat('en-US', {
    year: 'numeric',
    month: 'long', // 显示完整月份名称
    day: 'numeric'
  }).format(date);
};

// 测试一下
console.log(formatDate("2018-04-01T00:00:00.000Z")); // 输出 "April 1, 2018"

⚠️ 注意:如果你的项目需要兼容IE11这类旧浏览器,可能需要引入intl polyfill,但现在大部分现代项目(比如用React脚手架创建的)已经默认支持了。

方法二:手动解析日期组件(适合精细控制)

如果你想完全自己掌控逻辑,或者担心某些环境下Intl的支持问题,可以手动拆分ISO日期的各个部分,然后映射月份名称:

const formatDateManual = (isoDate) => {
  // 定义完整月份名称数组
  const months = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'
  ];
  
  const date = new Date(isoDate);
  
  // 注意用UTC方法,避免本地时区影响(因为输入的是UTC格式的ISO日期)
  const monthName = months[date.getUTCMonth()];
  const day = date.getUTCDate();
  const year = date.getUTCFullYear();
  
  return `${monthName} ${day}, ${year}`;
};

// 测试
console.log(formatDateManual("2018-04-01T00:00:00.000Z")); // 输出 "April 1, 2018"
在React组件中的实现示例

不管是函数组件还是类组件,都能轻松集成上面的格式化逻辑。这里给你几个常用的写法:

1. 直接在组件内格式化

import React from 'react';

const DateDisplay = ({ isoDate }) => {
  // 处理无效日期的容错逻辑
  const getFormattedDate = () => {
    if (!isoDate) return 'Invalid Date';
    const date = new Date(isoDate);
    if (isNaN(date.getTime())) return 'Invalid Date';
    
    return new Intl.DateTimeFormat('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    }).format(date);
  };

  return <p>Formatted Date: {getFormattedDate()}</p>;
};

// 使用组件
// <DateDisplay isoDate="2018-04-01T00:00:00.000Z" />

2. 封装成自定义Hook(推荐React最佳实践)

如果多个组件都需要日期格式化,可以把逻辑封装成自定义Hook,复用性更强:

import React, { useState, useEffect } from 'react';

const useFormattedDate = (isoDate) => {
  const [formattedDate, setFormattedDate] = useState('');

  useEffect(() => {
    if (!isoDate) {
      setFormattedDate('Invalid Date');
      return;
    }

    const date = new Date(isoDate);
    if (isNaN(date.getTime())) {
      setFormattedDate('Invalid Date');
    } else {
      setFormattedDate(
        new Intl.DateTimeFormat('en-US', {
          year: 'numeric',
          month: 'long',
          day: 'numeric'
        }).format(date)
      );
    }
  }, [isoDate]); // 当isoDate变化时自动重新格式化

  return formattedDate;
};

// 使用Hook的组件
const DateDisplay = ({ isoDate }) => {
  const formattedDate = useFormattedDate(isoDate);
  return <p>Formatted Date: {formattedDate}</p>;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:05:36