Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Subtracting months from current date is returning unexpected results. Same Month (March) is being returned twice

I have created a method that returns the past months according to the current date and how many months from the past you need, seems like the javascript date object is behaving wrongly.

I guess the problem has only popped up today as it's the 29th of the current month and subtracting 1 month from 29 March which is supposed to be 29 February (doesn't exist) lead javascript to fallback to +1 day...

Can someone please suggest a great fix for this. Thanks ๐Ÿ™Œ

export type Config = {
  n: number;
  i18n: i18n;
};

export default function NMonthsAgo(config: Config): MonthsAgo[] {
  const date = new Date();
  const { i18n } = config;
  let { n } = config;
  n = Math.max(n, 0);
  // add one month in future to include the current one.
  date.setMonth(date.getMonth() + 1);
  return Array.from({ length: n || 1 })
    .map(() => {
      date.setMonth(date.getMonth() - 1);
      console.log(date.toDateString()); ===> console print.
      return {
        monthName: formatDate(i18n, date, { month: 'long' }),
        monthNameShort: formatDate(i18n, date, { month: 'short' }),
        year: formatDate(i18n, date, { year: 'numeric' }),
      };
    })
    .reverse();
}

Output:

NMonthsAgo.js:36 Wed Dec 29 2021
NMonthsAgo.js:36 Mon Nov 29 2021
NMonthsAgo.js:36 Fri Oct 29 2021
NMonthsAgo.js:36 Wed Sep 29 2021
NMonthsAgo.js:36 Sun Aug 29 2021
NMonthsAgo.js:36 Thu Jul 29 2021
NMonthsAgo.js:36 Tue Jun 29 2021
NMonthsAgo.js:36 Sat May 29 2021
NMonthsAgo.js:36 Thu Apr 29 2021
NMonthsAgo.js:36 Mon Mar 29 2021 <=== Mars is returned twice... 
NMonthsAgo.js:36 Mon Mar 01 2021 <=== Mars is returned twice...
NMonthsAgo.js:36 Mon Feb 01 2021
NMonthsAgo.js:36 Fri Jan 01 2021
NMonthsAgo.js:36 Wed Dec 29 2021
about 4 years ago ยท Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!