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

如何用Date::toLocaleDateString()自定义格式化日期的分隔符?

实现"Jun/09/2023"格式的日期输出

toLocaleDateString本身没有提供直接修改分隔符的配置项,不过可以通过两种方式实现你想要的格式:

方式1:手动拼接各日期部分(推荐)

分别提取月份缩写、两位日期和四位年份,再用/拼接,这种方式不依赖toLocaleDateString的输出格式,兼容性和稳定性更好:

const now = new Date();
const monthShort = now.toLocaleDateString('en-US', { month: 'short' });
const dayTwoDigit = now.toLocaleDateString('en-US', { day: '2-digit' });
const yearFull = now.toLocaleDateString('en-US', { year: 'numeric' });
const formattedDate = `${monthShort}/${dayTwoDigit}/${yearFull}`;
// 输出示例:"Jun/09/2023"

方式2:替换原结果中的分隔符

基于你现有的代码,直接替换返回字符串里的空格和逗号即可:

const oDate = new Date().toLocaleDateString('en-US', { 
  year: "numeric", 
  day: "2-digit", 
  month: "short"
});
const formattedDate = oDate.replace(', ', '/').replace(' ', '/');
// 输出示例:"Jun/09/2023"

注意:第二种方式依赖en-US locale返回的固定格式("Jun 09, 2023"),如果后续环境对该locale的日期格式输出有调整,可能会失效,因此更推荐第一种方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:17:05