Home > Software design >  How can i get all the previous months since today?
How can i get all the previous months since today?

Time:08-12

How can i do this same function of this with moment js or other library like luxon, i want to get all the previos 'n' months since the current day

for example currently is agost, i need Feb, Mar, Apr, May, Jun, Jul, the names should be in short

console.log(getPreviousNMonths(6))
 function uInt(n, ceil) {
    while (n < 0) {
        n  = ceil
    }
    return n % ceil
}
function getPreviousNMonths(n) {
    const date = new Date()
    const d = new Date(date.getTime())
    const formatter = new Intl.DateTimeFormat([], { month: 'short' })
    const names = []

    for (let i = 0; i < n; i  = 1) {
        d.setMonth(uInt(d.getMonth() - 1, 12))
        names.push(formatter.format(d))
    }
    return names.reverse()
}

CodePudding user response:

Using moment.js

const names = []

for (let i = 1; i <= n; i  = 1) {
    let monthName =  moment('2021-08-10').subtract(i, "month").startOf("month").format('MM');
    names.push(monthName)
}

Or using luxon

const names = []

for (let i = 1; i <= n; i  = 1) {
    let monthName =  DateTime.local().minus({ months: i }).toFormat("MM") 
    names.push(monthName)
}
  • Related