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

198
Views
Date() in js doesn't switch days correctly

I want to increase and decrease days in a date without changing other parts of the date. For example, when I have:

  • 31 December 2021 -> add one day -> 01 December 2021, or
  • 01 December 2021 -> subtract one day -> 31 December 2021

Below, is my increase day code. It works fine and I get what I want:

let cur_date = new Date();

setInterval(() => {
  let curMonth = cur_date.getMonth();
  cur_date.setDate(cur_date.getDate() + 1);
  if (cur_date.getMonth() !== curMonth) {
    cur_date.setMonth(curMonth);
  }
  console.log(cur_date.toLocaleString());
}, 1000);

My decrease day code does not work and I get 31 December 2021 after 01 November 2021:

let cur_date = new Date();

setInterval(() => {
  let curMonth = cur_date.getMonth();
  cur_date.setDate(cur_date.getDate() - 1);
  if (cur_date.getMonth() !== curMonth) {
    cur_date.setMonth(curMonth);
  }
  console.log(cur_date.toLocaleString());
}, 1000);

How to fix it?

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

0

This happens because November does not have 31 days, and so when you go one day back from 1 November, you get 31 October. Then you change the month so it would be 31 November, but JavaScript interprets that as 30 November + 1 day = 1 December.

To avoid this, perform a check before subtracting one day: if the date is 1, then first add a month, and then let the subtraction of 1 day happen:

let cur_date = new Date();

setInterval(() => {
  let curMonth = cur_date.getMonth();
  if (cur_date.getDate() === 1) { // Do the check here, before subtracting 1 day
    cur_date.setMonth(curMonth + 1); // Go temporary to next month
  }
  cur_date.setDate(cur_date.getDate() - 1);
  console.log(cur_date.toLocaleString());
}, 1000);

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!