JavaScript如何将Saturday 14th August类日期字符串转为14/08/2021格式
JavaScript 日期格式转换解决方案
原生JS实现(无需引入第三方依赖)
核心逻辑是先去除日期中的序数词后缀(st/nd/rd/th),再解析为Date对象后格式化输出:
/** * 转换日期格式 * @param {string} inputStr 输入的日期字符串 格式如 'Saturday 14th August' * @param {number} [targetYear = new Date().getFullYear()] 目标年份,默认取当前年 * @returns {string} 格式为 dd/mm/yyyy 的日期字符串 */ function convertCustomDate(inputStr, targetYear = new Date().getFullYear()) { // 清除日期中的序数词后缀 const cleanedDateStr = inputStr.replace(/(\d+)(st|nd|rd|th)/, '$1'); // 拼接年份后转换为Date对象 const dateObj = new Date(`${cleanedDateStr} ${targetYear}`); // 校验日期合法性 if (isNaN(dateObj.getTime())) { throw new Error('输入的日期格式不符合要求'); } // 日期补零处理 const day = String(dateObj.getDate()).padStart(2, '0'); // 月份从0开始计数需要+1 const month = String(dateObj.getMonth() + 1).padStart(2, '0'); const year = dateObj.getFullYear(); return `${day}/${month}/${year}`; } // 测试调用 输出: 14/08/2021 console.log(convertCustomDate('Saturday 14th August', 2021));
注意事项
- 输入的原始日期字符串没有携带年份信息,需要手动指定目标年份,不指定时默认取当前系统年份
- 如果需要适配UTC时区,将
getDate/getMonth/getFullYear替换为getUTCDate/getUTCMonth/getUTCFullYear即可 - 正则匹配兼容所有序数词场景,1st、2nd、3rd、4th等后缀都可以正常清除
可选方案(使用第三方日期库)
如果项目中已经引入dayjs等日期处理库,可以直接调用库的解析和格式化方法,代码更简洁:
import dayjs from 'dayjs'; import customParseFormat from 'dayjs/plugin/customParseFormat'; dayjs.extend(customParseFormat); function convertDateWithDayjs(inputStr, targetYear = new Date().getFullYear()) { const cleanedStr = inputStr.replace(/(\d+)(st|nd|rd|th)/, '$1'); return dayjs(`${cleanedStr} ${targetYear}`, 'dddd D MMMM YYYY').format('DD/MM/YYYY'); }
内容的提问来源于stack exchange,提问作者PeraDev
相关产品推荐
相关产品推荐

