You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

React JS中如何从ISO格式created_date提取年、月、日并格式化为指定日期样式展示?

处理React中的日期格式需求

嘿,这个需求在React里处理起来其实挺简单的!我来给你拆解两种需求的实现方法,既有原生JS的方案,也有借助第三方库的选项,你可以根据项目情况来选:

一、提取年、月、日信息

你可以直接用JavaScript原生的Date对象解析后端返回的ISO标准日期,再通过内置方法提取对应的字段:

const createdDate = "2021-09-27T06:10:07.972531Z";
const dateObj = new Date(createdDate);

// 提取年、月、日
const year = dateObj.getFullYear(); // 输出:2021
// 注意:getMonth()返回0-11的数字,所以要+1得到实际月份
const month = dateObj.getMonth() + 1; // 输出:9
const day = dateObj.getDate(); // 输出:27

如果需要月份的英文全称(比如后面格式化要用到),可以提前定义一个月份数组来映射:

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"];
const monthName = monthNames[dateObj.getMonth()]; // 输出:September

二、格式化为「31 December,2020」样式

这里给你三种常用方案:

方案1:原生JS手动拼接(无额外依赖)

结合上面提取的字段,直接拼接成目标格式,适合不想加依赖的小项目:

// 定义格式化函数
function formatDate(dateStr) {
  const dateObj = new Date(dateStr);
  const monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"];
  const day = dateObj.getDate();
  const monthName = monthNames[dateObj.getMonth()];
  const year = dateObj.getFullYear();
  return `${day} ${monthName}, ${year}`;
}

// 在React组件中使用
function MyComponent() {
  const createdDate = "2021-09-27T06:10:07.972531Z";
  return <div className="date-display">{formatDate(createdDate)}</div>;
  // 渲染结果:27 September, 2021
}

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

JS原生的国际化API可以直接生成符合要求的格式,不用手动维护月份数组,代码更简洁优雅:

function formatDate(dateStr) {
  const dateObj = new Date(dateStr);
  // 配置格式化规则:日为数字,月为全称,年为数字
  return new Intl.DateTimeFormat('en-US', {
    day: 'numeric',
    month: 'long',
    year: 'numeric'
  }).format(dateObj);
}

// 组件中使用效果和方案1完全一致

方案3:借助第三方日期库(如date-fns

如果项目中已经在用日期处理库,那会更省心。这里推荐date-fnsmoment.js已进入维护模式,不建议新项目使用):

首先安装依赖:

npm install date-fns

然后在组件中使用:

import { format } from 'date-fns';

function MyComponent() {
  const createdDate = "2021-09-27T06:10:07.972531Z";
  // 用指定格式字符串生成结果
  const formattedDate = format(new Date(createdDate), "d MMMM, yyyy");
  return <div>{formattedDate}</div>; // 输出:27 September, 2021
}

小提示:如果你的项目需要处理多语言场景,Intl.DateTimeFormatdate-fns都能轻松适配,只需要切换对应的语言参数即可。

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

火山引擎 最新活动