You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript获取指定月数前的月末日期——月末边界场景代码修复问询

Fixing "N Months Ago End of Month" Calculation in JavaScript

Got it, let's fix this date calculation issue you're running into. The problem here is how JavaScript's setMonth() handles dates that don't exist in the target month—like trying to set February 29, 2021, which rolls over to March 1 instead of clamping to the last valid day of February. That's why your code ends up returning March 31 instead of February 28 for the example you mentioned.

The Fix: Shift Your Approach

Instead of subtracting months from the current date first, we should:

  • Get the first day of the current month (this avoids any date rollover issues, since every month has a 1st)
  • Subtract i months from that first day
  • Then get the last day of that resulting month

Modified Code

Here's the updated version of your script that implements this logic:

<!DOCTYPE html>
<html>
<body>
<h2>RPA Date Sandbox</h2>
<p id="d1"></p>
<p id="d2"></p>
<p id="d3"></p>
<p id="Result1"></p>
<script>
var i = 2;
var d1 = new Date();
// Step 1: Create date for the first day of current month
var firstDayOfCurrentMonth = new Date(d1.getFullYear(), d1.getMonth(), 1);
// Step 2: Subtract i months from the first day (no rollover risk)
var targetMonthStart = new Date(firstDayOfCurrentMonth.setMonth(firstDayOfCurrentMonth.getMonth() - i));
// Step 3: Get last day of the target month
var d3 = new Date(targetMonthStart.getFullYear(), targetMonthStart.getMonth() + 1, 0);
// Format the result
var result1 = d3.getDate()+'/'+((d3.getMonth()<9)?'0'+(d3.getMonth()+1):(d3.getMonth())+1)+'/'+d3.getFullYear();

// Update DOM elements
document.getElementById("d1").innerHTML = "d1 (current date): " + new Date()
document.getElementById("d2").innerHTML = "Target month start: " + targetMonthStart
document.getElementById("d3").innerHTML = "End of target month: " + d3
document.getElementById("Result1").innerHTML = "Result1: " + result1
</script>
</body>
</html>

Why This Works

Let's test your example scenario (current date = April 29, 2021):

  1. firstDayOfCurrentMonth becomes April 1, 2021
  2. Subtract 2 months gives us February 1, 2021 (no rollover here—February always has a 1st)
  3. new Date(2021, 2, 0) gives us the last day of February 2021, which is February 28, 2021 (since March is month index 2, passing 0 as the day gets the last day of the previous month)

This approach will work for any date, whether it's the end of the month or not, because we're always starting from a safe date (the 1st) before subtracting months.

内容的提问来源于stack exchange,提问作者JonasArnout

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:12:38