如何在JavaScript中将X年Y月Z天格式的字符串转换为对应总天数
JavaScript实现“X years Y months Z days”字符串转总天数教程
实现前提说明
你给出的示例结果832是基于「1年=365天、1月=30天」的固定换算规则得到的,该规则不考虑闰年、大小月差异,适合粗略计算场景。如果需要真实日历的精确天数,需要指定基准日期再做计算。
实现思路
- 用正则匹配字符串中的数值和对应的时间单位,自动兼容单复数单位(比如
year/years都可识别) - 按预设的换算规则累加计算总天数
完整代码实现
function calcTotalDays(timeStr) { // 固定换算规则,和示例结果对齐 const CONVERT_RULE = { year: 365, month: 30, day: 1 }; let totalDays = 0; // 正则匹配所有数值+单位的组合 const matchReg = /(\d+)\s*(years?|months?|days?)/gi; let matchRes; while((matchRes = matchReg.exec(timeStr)) !== null) { const num = parseInt(matchRes[1]); // 把单位转成单数做映射匹配 const unit = matchRes[2].toLowerCase().replace(/s$/, ''); totalDays += num * CONVERT_RULE[unit]; } return totalDays; } // 测试示例 var d = "2 years 3 months 12 days"; console.log(calcTotalDays(d)); // 输出结果为832
真实日历精确天数扩展实现(可选)
如果需要计算对应时间间隔在真实日历里的实际天数,可指定基准日期计算,示例如下:
function calcActualTotalDays(timeStr, baseDate = new Date()) { // 复制基准日期避免修改原对象 const targetDate = new Date(baseDate); const matchReg = /(\d+)\s*(years?|months?|days?)/gi; let matchRes; while((matchRes = matchReg.exec(timeStr)) !== null) { const num = parseInt(matchRes[1]); const unit = matchRes[2].toLowerCase().replace(/s$/, ''); switch(unit) { case 'year': targetDate.setFullYear(targetDate.getFullYear() - num); break; case 'month': targetDate.setMonth(targetDate.getMonth() - num); break; case 'day': targetDate.setDate(targetDate.getDate() - num); break; } } // 计算两个日期的天数差 const diffTime = baseDate.getTime() - targetDate.getTime(); return Math.ceil(diffTime / (1000 * 60 * 60 * 24)); }
内容的提问来源于stack exchange,提问作者Elvin
相关产品推荐
相关产品推荐

