长日期转指定格式:缺失日/月时返回对应空值的技术问题
解决日期转换中缺失部分返回空值的问题
你的原始方法对于完整日期转换很有效,但问题在于Date构造函数会自动补全缺失的日/月(比如输入"march 2018"时,它会默认把日期设为当月1号),导致无法识别缺失的部分。要实现缺失部分返回空值的需求,我们需要先手动解析日期字符串,判断哪些部分存在,再分别处理。
实现思路
- 建立英文月份到两位数字的映射表,方便快速转换月份格式。
- 用正则表达式匹配不同格式的输入日期(完整日期、缺日、缺月等场景)。
- 根据匹配结果,提取存在的年、月、日部分,缺失的部分直接留空。
- 将各部分按
YYYYMMDD的格式拼接,缺失的部分不填充默认值。
代码实现
function formatCustomDate(dateStr) { // 英文月份转两位数字的映射 const monthMap = { january: '01', february: '02', march: '03', april: '04', may: '05', june: '06', july: '07', august: '08', september: '09', october: '10', november: '11', december: '12' }; // 匹配完整日期:"日 月 年" 格式(比如 "2 march 2018") const fullDateMatch = dateStr.match(/^(\d{1,2}) (\w+) (\d{4})$/i); if (fullDateMatch) { const day = fullDateMatch[1].padStart(2, '0'); const month = monthMap[fullDateMatch[2].toLowerCase()]; const year = fullDateMatch[3]; return `${year}${month}${day}`; } // 匹配缺日的日期:"月 年" 格式(比如 "march 2018") const monthYearMatch = dateStr.match(/^(\w+) (\d{4})$/i); if (monthYearMatch) { const month = monthMap[monthYearMatch[1].toLowerCase()]; const year = monthYearMatch[2]; return `${year}${month}`; // 日部分缺失,返回空(不拼接日的内容) } // 匹配缺月的日期:"日 年" 格式(比如 "2 2018") const dayYearMatch = dateStr.match(/^(\d{1,2}) (\d{4})$/i); if (dayYearMatch) { const day = dayYearMatch[1].padStart(2, '0'); const year = dayYearMatch[2]; return `${year}${day}`; // 月部分缺失,返回空(不拼接月的内容) } // 如果输入格式不匹配,可根据需求返回空或原字符串 return ''; } // 测试示例 console.log(formatCustomDate("2 march 2018")); // 输出:"20180302" console.log(formatCustomDate("march 2018")); // 输出:"201803" console.log(formatCustomDate("2 2018")); // 输出:"201802"
关键说明
- 用正则表达式精准匹配不同输入格式,彻底避免
Date对象自动补全的问题。 - 借助
padStart(2, '0')确保日和月始终是两位数字(比如"2"转为"02")。 - 针对每种缺失场景单独处理,确保缺失部分对应的位置不填充任何内容,完全符合你要的空值需求。
内容的提问来源于stack exchange,提问作者Udit Gogoi
相关产品推荐
相关产品推荐

