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

126
Views
JS problem with the month of February in non-leap months

I am implementing a simple calendar, but i have a problem with all non-leap fever months.

If you click on next until February 2023, March is shown, if you advance until 2024 (which is a leap), everything works, how can I solve?

let nav = 0;

let test = () => {
  const dt = new Date();
  dt.setMonth(new Date().getMonth() + nav);
  const day = dt.getDate();
  const month = dt.getMonth();
  const year = dt.getFullYear();
  const monthName = `${dt.toLocaleDateString("en", { month: "long" })} ${year}`;
  
  document.getElementById('feedBack').innerHTML = 'Nav: ' + nav + ' - Day: ' + 1 + ' - Month: ' + month + ' ( <b>' + monthName + '</b> ) - Year: ' + year;
}

test();
#feedBack {margin-top:10px}
<button onclick="nav--;test()">Prev</button>
<button onclick="nav=0;test();">Current</button>
<button onclick="nav++;test();">Next</button>

<div id="feedBack"></div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you wait for two days the problem will be solved hehe (today is 29/06, you are iterating over, 29/07, 29/08, etc.).

Or you could change day of the month object before incrementing the month.

let nav = 0;

let test = () => {
  const dt = new Date();
  dt.setDate(1); // this will move to the first day of the current month
  dt.setMonth(new Date().getMonth() + nav);
  const month = dt.getMonth();
  const year = dt.getFullYear();
  const monthName = `${dt.toLocaleDateString("en", { month: "long" })} ${year}`;
  
  document.getElementById('feedBack').innerHTML = 'Nav: ' + nav + ' - Day: ' + 1 + ' - Month: ' + month + ' ( <b>' + monthName + '</b> ) - Year: ' + year;
}

test();
#feedBack {margin-top:10px}
<button onclick="nav--;test()">Prev</button>
<button onclick="nav=0;test();">Current</button>
<button onclick="nav++;test();">Next</button>

<div id="feedBack"></div>

about 4 years ago · Juan Pablo Isaza Report
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!