How to get the last day of 24 months?

Asked by At

Regards,

Given the current date, I would like to know the last day of the month for the last 24 months. Im trying to get an output similar to this:

30/11/2018 for current month -1

31/10/2018 for current month -2

...

31/12/2016 for current month -24

I've tried searching trough SO but I couldn't find a similar question.

Any help? :)

Edit: Based on Jalees code, I've come with this code, that I think it does what I need:

for(i=0;i<24;i++)
{
 d = new Date();
 d.setMonth(d.getMonth() + (1 - (i + 1)));
 d.setDate(0);
 $('#aaaaa').append($('<option>', {value: 'x', text: d.getDate() + '/' + (((d.getMonth() + 1).length == 1) ? '0'+''+(d.getMonth() + 1) : d.getMonth() + 1) + '/' + d.getFullYear()}));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="aaaaa"></select>

2 Answers

2
charlietfl On Best Solutions

Use loop index to subtract from current month to build a new date for each month and set the day to zero to get last day of prior month

Example using Array#from():

const curr = new Date();

function getPrevMonth(_,i){
   const prev = new Date(curr.getFullYear(), curr.getMonth()-i, 0)
   return [prev.getDate(), prev.getMonth()+1, prev.getFullYear()].join('/')// format as desired
}
const months = Array.from({length:24}, getPrevMonth);

console.log(months)

1
Jalees Ahmad On

you can use this technique . for month February you can use 1 and for March 2 and continue.

var month = 0; // January
var d = new Date(2008, month + 1, 0);
alert(d); // last day in January