如何用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
相关产品推荐
相关产品推荐

