Home > OS >  From current date working backwards to a certain date, display month and year
From current date working backwards to a certain date, display month and year

Time:08-24

So the problem I'm trying to solve is something like this.. given a date (early join date) work backwards from now. so in this example, I have a date of 2021, July 25th.

I need to put this in an array moving backwards from now in a certain format. So like..

August 2022 July 2022 June 2022 May 2022 April 2022 March 2022 February 2022 January 2022 December 2021 ... July 2021

I got this to the point where this works for two years, not sure how to refactor this in a way where I can do this for x # of years.. also is this easier with moment?

function getMonthDifference(startDate: Date, endDate: Date) {
  return (
    endDate.getMonth() -
    startDate.getMonth()  
    12 * (endDate.getFullYear() - startDate.getFullYear())
  )
}

const earliestDateJoined = "2020-07-25"
const now = new Date()
const earliestDate = new Date(earliestDateJoined)


for (let i = 0; i < getMonthDifference(earliestDate, now)   1; i  ) {
  let month = new Date().getMonth()   1 - i
  let year = new Date().getFullYear()
  // console.log("before", year, month)
  if (month < 1) {
    month = month   12
    year = year - 1
    if (month < 1) {
      month = month   12
      year = year - 1
    }
  }
  const nameMonth = {
    1: "Jan",
    2: "Feb",
    3: "Mar",
    4: "Apr",
    5: "May",
    6: "Jun",
    7: "Jul",
    8: "Aug",
    9: "Sep",
    10: "Oct",
    11: "Nov",
    12: "Dec"
  }
  console.log(year   " Year "   nameMonth[month]   " Month ")
}

CodePudding user response:

You're looking for the while loop.

I imagine you started with one if (month < 1), but you noticed it broke when going back more than a year. So you added another, but you know you can't keep doing that. If you used a while loop instead, you could repeat the same arithmetic until month >= 1.

That being said, it would probably be easier to use something like this:

const yearsAgo = Math.floor(monthsAgo/12);
const monthsAgoRemainder = monthsAgo % 12;

That way you can calculate the number of years from the total number of months in one go.

Interestingly, the for loop you use earlier would probably also be better as a while loop. You use getMonthDifference to figure out ahead of time how many iterations you'll need, but with a while loop you can just wait until you hit the target date. The downside is you must ensure the while loop always exits.

As for using moment or a similar library: yes, that'll probably simplify the whole thing a lot. I mention the while loops because it's an important tool to have in your back pocket.

CodePudding user response:

If you set the day of month of both values to 1, you can simply loop over now, pushing a formatted date into an array and then decrementing by 1 month until it is less than the earliestDate value:

const earliestDateJoined = "2020-07-25"
const earliestDate = new Date(earliestDateJoined)
const now = new Date()

// set the day of month on both values to be 1 to make it easier to loop
now.setDate(1)
earliestDate.setDate(1)

// format the date
formatDate = (d) => {
  const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
  return `${months[d.getMonth()]} ${d.getFullYear()}`
}

let months = []
while (now >= earliestDate) {
  months.push(formatDate(now))
  now.setMonth(now.getMonth()-1)
}

console.log(months)

CodePudding user response:

function getMonths(startDate, endDate) {
    let arr = [];
    let startMoment = moment(startDate).startOf('month');
    let endMoment = moment(endDate).startOf('month');
    do {
        arr.push(startMoment.format('MMMM YYYY'));
    } while(startMoment.add(1, 'month').diff(endMoment) <= 0);
    return arr;
}
let arr = getMonths(new Date('2020-07-25'), new Date());
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>

  • Related