使用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
imonths 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):
firstDayOfCurrentMonthbecomes April 1, 2021- Subtract 2 months gives us February 1, 2021 (no rollover here—February always has a 1st)
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

