admin管理员组

文章数量:1317909

This is the stack answer I followed:

To create:

let start = new Date(data.start_date);
let end   = new Date(start.setMonth(start.getMonth() + 1));

start = start.toISOString().split('T')[0]
end   = end.toISOString().split('T')[0]

console.log(start, end);
  • Expected: start: 2022-07-23 end: 2022-08-23
  • Actual: start: 2022-07-23 end: 2022-07-23

Is this not how you properly add a month to a date?

The stack answer states it is correct, am I missing something?

This is the stack answer I followed:

  • https://stackoverflow./a/5645110/1270259

To create:

let start = new Date(data.start_date);
let end   = new Date(start.setMonth(start.getMonth() + 1));

start = start.toISOString().split('T')[0]
end   = end.toISOString().split('T')[0]

console.log(start, end);
  • Expected: start: 2022-07-23 end: 2022-08-23
  • Actual: start: 2022-07-23 end: 2022-07-23

Is this not how you properly add a month to a date?

The stack answer states it is correct, am I missing something?

Share Improve this question edited Apr 28, 2023 at 17:02 ℛɑƒæĿᴿᴹᴿ 5,3765 gold badges41 silver badges60 bronze badges asked Jun 2, 2022 at 19:43 TheWebsTheWebs 12.9k32 gold badges115 silver badges220 bronze badges 1
  • You should check the times also, it's probably a time zone issue. – Pointy Commented Jun 2, 2022 at 19:49
Add a ment  | 

2 Answers 2

Reset to default 5

By calling start.setMonth you end up updating the month on both dates. (This is noted in one of the ments on the answer you followed, but not in the answer itself.)

Separate the statements to only affect the date you want changed:

let start = new Date();
let end = new Date(start);
end.setMonth(end.getMonth() + 1);

console.log(start, end)

Simply using getMonth()+1 can give undesirable results. For example, if you are puting due dates for monthly payments you might want to ensure that no months are skipped. Adding a month to March 31 results in May 1, because April only has 30 days.

let start = new Date("31-March-2024")
let end = new Date(start)
end.setMonth(end.getMonth() + 1)
console.log(start.toString(), end.toString())      // end date is May 1

You can detect this "month overflow" by checking getDate() values for the start and end dates; when they are different, use 0 as the resulting day of the month, which is the last day of the month prior to the overflow. Example:

function addMonths(date, months) {
  let temp = new Date(date)
  temp.setMonth(temp.getMonth() + months)
  if (temp.getDate() != date.getDate()) temp.setDate(0)
  return temp
}

let start = new Date("31-March-2024")
console.log(start.toString(), addMonths(start, 1).toString())    // end date is April 30
console.log(start.toString(), addMonths(start, 2).toString())    // end date is May 31

本文标签: javascriptAdding months to date in jsStack Overflow