Home > front end >  Change day in new Date() js without rollover month, year or time
Change day in new Date() js without rollover month, year or time

Time:11-11

Hello everyone. Can you help me with this kind of question? I want to encrease days in date string, so code is kind like this.

var date = new Date()
date.setDate(date.getDate()   1)

The problem is that i want to change only days without month, years or time (h m s). So, for example if i have date 31 december 2021 and i encrease day by one i want to get 01 december 2021 and not 01 january 2022. Is it possible in JS?

CodePudding user response:

You'll just have to manually check and adjust if needed. Here's an example function:

var date = new Date('12/31/2021');

incremenetLoopingDate(date);
console.log(date);

function incremenetLoopingDate(date){
  var mo = date.getMonth();
  date.setDate(date.getDate()   1);
  if(date.getMonth() !== mo){
    date.setMonth(mo);
  }
  return date;
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Similar to the other answer, but simpler. Just check if the incremented date is 1 and if so, set to the previous month. Note that this modifies the passed date.

function incrementMonthLoop(date = new Date()) {
  date.setDate(date.getDate()   1);
  if (date.getDate() == 1) date.setMonth(date.getMonth() - 1);
  return date;
}

console.log(
  incrementMonthLoop(new Date(2021, 11, 31)).toDateString()
);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related