如何在JavaScript或TypeScript中获取系统ShortDateFormat?
获取系统短日期格式(ShortDateFormat)

需求:在JavaScript/TypeScript中获取系统的ShortDateFormat。例如系统显示日期为“27-Oct-22”时,输出对应的格式串“dd-MMM-yy”。
实现方案
JavaScript/TypeScript没有原生API直接返回系统的日期格式模板,但可以通过生成已知日期的格式化结果,反向推导格式串:
function getShortDateFormat(): string { // 固定测试日期:2022年10月27日,便于匹配替换 const testDate = new Date(2022, 9, 27); // 获取系统默认短日期格式的字符串 const systemFormattedDate = testDate.toLocaleDateString(undefined, { dateStyle: 'short' }); // 替换已知日期片段为对应格式占位符 let format = systemFormattedDate .replace('27', 'dd') .replace('Oct', 'MMM') .replace('22', 'yy') .replace('10', 'MM') .replace('2022', 'yyyy'); // 兼容单数字日/月的情况 if (systemFormattedDate.includes('7') && !systemFormattedDate.includes('27')) { format = format.replace('7', 'd'); } const monthMatches = systemFormattedDate.match(/\d{1,2}/g); if (monthMatches?.length >= 2) { const monthPart = monthMatches[1]; if (monthPart.length === 1 && !format.includes('MM')) { format = format.replace(monthPart, 'M'); } } return format; } // 调用示例 console.log(getShortDateFormat());
说明
toLocaleDateString(undefined, { dateStyle: 'short' })会根据系统区域设置返回对应的短日期字符串- 通过替换测试日期的固定值(27、Oct、22等)为标准格式占位符,得到系统对应的格式模板
- 代码兼容不同区域的格式差异,比如美式
MM/dd/yy、欧式dd/MM/yy、英式dd-MMM-yy等
内容的提问来源于stack exchange,提问作者Suraj Verma
相关产品推荐
相关产品推荐

