JavaScript日期计算:指定28日及累加月份问题求助
问题2:固定日期为当月28日(过28日则设为下月28日),再累加指定月份数
先看你的.NET代码逻辑:它是先对发票日期添加指定月份,再取新日期的年、月,最后把日设为28。对应到JavaScript,我们需要先处理“固定到28日”的逻辑,再完成月份累加。
先分析你尝试的代码问题:
你的代码有几个明显的错误:
- 用字符串
"28"和数字day比较,虽然JS会隐式转换,但不规范且容易引发意外问题 - 逻辑混乱:
if (day <= "28") result += day ="28";这里的赋值和拼接逻辑完全错误,也没有处理月份进位 - 没有正确实现“过28日则跳下月28日”的核心逻辑
正确的实现代码:
function getAdjustedDateWithAddedMonths(baseDate, monthsToAdd) { const adjustedDate = new Date(baseDate); const day = adjustedDate.getDate(); // 第一步:调整到当月或下月28日 if (day > 28) { // 过了28日,设为下月28日 adjustedDate.setMonth(adjustedDate.getMonth() + 1); } adjustedDate.setDate(28); // 第二步:累加指定月份数 adjustedDate.setMonth(adjustedDate.getMonth() + monthsToAdd); return adjustedDate; } // 使用示例:今天是2024年3月30日,加5个月 const today = new Date(2024, 2, 30); const result = getAdjustedDateWithAddedMonths(today, 5); console.log(result.toLocaleDateString()); // 输出"10/28/2024"(先跳到4月28日,再加5个月到10月28日)
如果要完全对齐你的.NET代码逻辑(先加月份再设为28日),可以用这个版本:
function alignWithDotNetLogic(invoiceDate, amountOfMonths) { const tempDate = new Date(invoiceDate); // 先添加指定月份 tempDate.setMonth(tempDate.getMonth() + amountOfMonths); // 再设置为当月28日 tempDate.setDate(28); return tempDate; }
这个写法和你的.NET代码DateSerial(Year(DateAdd("m", AmountOfMonths, CDate(Invoice_date))), Month(DateAdd(DateInterval.Month, AmountOfMonths, CDate(Invoice_date))), 28)逻辑完全一致。
内容的提问来源于stack exchange,提问作者Greg




