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

如何在JavaScript中将ISO格式日期转为‘1st June 2021’格式?

解决ISO日期转"1st June 2021"格式的问题

原生toDateString()方法的输出格式是固定的,无法直接生成带序数词(st/nd/rd/th)的目标格式,需要手动处理日期的各个组成部分,以下是两种可行方案:

方案一:手动拼接日期各部分

先提取日期的日、月份全称、年份,再给日期数字添加对应的序数词后缀:

// 注意:ISO日期字符串必须用引号包裹,原代码存在语法错误
const dat = '2021-06-01T00:00:00.000Z';
const d = new Date(dat);

// 获取月份全称(如June)
const month = d.toLocaleString('en-US', { month: 'long' });
// 获取年份
const year = d.getFullYear();
// 获取UTC日期(避免时区影响,若需本地时区则用getDate())
const day = d.getUTCDate();

// 生成序数词后缀的工具函数
const getOrdinalSuffix = (num) => {
  if (num > 3 && num < 21) return 'th';
  switch (num % 10) {
    case 1: return 'st';
    case 2: return 'nd';
    case 3: return 'rd';
    default: return 'th';
  }
};

// 拼接成目标格式
const formattedDate = `${day}${getOrdinalSuffix(day)} ${month} ${year}`;
console.log(formattedDate); // 输出:1st June 2021

方案二:结合Intl.DateTimeFormat简化处理

利用国际化API获取基础格式,再替换日期部分为带序数词的版本:

const dat = '2021-06-01T00:00:00.000Z';
const d = new Date(dat);

// 先获取"June 1, 2021"格式的基础字符串
const baseDateStr = d.toLocaleString('en-US', { 
  year: 'numeric', 
  month: 'long', 
  day: 'numeric' 
});

// 替换日期数字为带序数词的形式
const formattedDate = baseDateStr.replace(/(\d+)/, (match) => {
  const num = parseInt(match);
  const suffix = (num > 3 && num < 21) ? 'th' : 
    { 1: 'st', 2: 'nd', 3: 'rd' }[num % 10] || 'th';
  return `${num}${suffix}`;
});

console.log(formattedDate); // 输出:1st June 2021

关键注意点

  • 原代码中const dat = 2021-06-06T00:00:00.000Z;存在语法错误,ISO日期必须以字符串形式赋值(加引号),否则会被解析为数学表达式导致错误。
  • 若业务需要基于本地时区而非UTC展示日期,将getUTCDate()替换为getDate()即可,但要注意时区转换可能导致日期数值变化。

内容的提问来源于stack exchange,提问作者Digvijay Singh Thakur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:50:15