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

如何在JavaScript日期的日、月、年之间添加短横线格式化日期

如何在JavaScript中将日期格式化为29-Jan-2021?

你现在用toLocaleString得到的是29 Jan 2021,要把空格换成连字符,有几种实用的解决办法:

方法一:直接替换字符串中的空格

最省事的方式就是把格式化后的字符串里的空格直接替换成-,一行代码就能搞定:

var newDate = new Date('2021-01-29T12:18:48.6588096Z')

const options = {
  year: 'numeric',
  month: 'short',
  day: 'numeric',
};

// 用replaceAll替换所有空格
const formattedDate = newDate.toLocaleString('en-UK', options).replaceAll(' ', '-');
console.log(formattedDate); // 输出 29-Jan-2021

如果要兼容不支持replaceAll的旧环境,用正则替换也可以:

const formattedDate = newDate.toLocaleString('en-UK', options).replace(/\s+/g, '-');

方法二:手动拼接日期各部分

这种方式更稳妥,能完全控制格式,避免不同locale可能带来的格式差异:

var newDate = new Date('2021-01-29T12:18:48.6588096Z')

// 定义英文月份的短缩写数组
const monthShortNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

// 原日期是UTC格式,用UTC相关方法避免时区偏移问题
const day = newDate.getUTCDate();
const month = monthShortNames[newDate.getUTCMonth()]; // 月份是0索引,直接取对应缩写
const year = newDate.getUTCFullYear();

// 手动拼接成目标格式
const formattedDate = `${day}-${month}-${year}`;
console.log(formattedDate); // 输出 29-Jan-2021

如果你的日期是本地时区,把getUTCDate()换成getDate(),getUTCMonth()换成getMonth(),getUTCFullYear()换成getFullYear()即可。

方法三:用formatToParts精确提取各部分

如果需要更规范的处理(比如应对复杂locale场景),可以用Intl.DateTimeFormat的formatToParts方法,把日期拆成各个组件再拼接:

var newDate = new Date('2021-01-29T12:18:48.6588096Z')

const formatter = new Intl.DateTimeFormat('en-UK', {
  year: 'numeric',
  month: 'short',
  day: 'numeric',
});

// 把日期拆成各个部分的对象数组
const dateParts = formatter.formatToParts(newDate);

// 提取需要的日、月、年部分
const day = dateParts.find(part => part.type === 'day').value;
const month = dateParts.find(part => part.type === 'month').value;
const year = dateParts.find(part => part.type === 'year').value;

const formattedDate = `${day}-${month}-${year}`;
console.log(formattedDate); // 输出 29-Jan-2021

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:25:19