0

I want to return the end of the month of i months ago. But near the end of the month my current code breaks because no every month has the same number of days. Today for example (29/04/2021) two months back should return the end of February, but date, 29/02/2021 does not exist, 01/03/2021 if used instead, which results in 31/03/2021 instead of 28/02/2021.

Please advise how to change my code to get the correct result even near the end of the month, thx!

<!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(); 
var d2 = new Date(d1.setMonth(d1.getMonth()-i)); 
var d3 = new Date(d2.getFullYear(),d2.getMonth()+1,0);
var result1 = d3.getDate()+'/'+((d3.getMonth()<9)?'0'+(d3.getMonth()+1):(d3.getMonth())+1)+'/'+d3.getFullYear();

document.getElementById("d1").innerHTML = "d1 (ignore setMonth): " + new Date()
document.getElementById("d2").innerHTML = "d2: " + d2
document.getElementById("d3").innerHTML = "d3: " + d3
document.getElementById("Result1").innerHTML = "Result1: " + result1

</script>

</body>
</html>
sd_dewasurendra
  • 383
  • 6
  • 22

0 Answers0