Home > OS >  Date-fns Unexpected results when adding months
Date-fns Unexpected results when adding months

Time:06-08

I am using date-fns for the first time in my project. I need to give user the ability to add a month to current date. I'm wondering how is this supposed to work with different length months?

I tried different months with 30 and 31 days and I cannot make sense of it. If I add a month to July 1, 2022 I get July 31, 2022 (I would expect Aug 1st) but if I add a month to July 7 I get Aug, 7, 2022.

Also, I added a month to Feb, 15 2023 and the result I got is Mar, 14 2023 (was expecting March 15). Then when I add a month to Feb 1, 2023 I get Mar 1, 2023 which is good.

Here is my code:

export const addMonth(date, numOfMonths) {
  return addMonths(Date.parse(date), numOfMonths)
  // date is a date string
}

Appreciate if someone can advise. Thanks

CodePudding user response:

as you havn't given any examples of what you have done its impossible to tell you where you have gone wrong a quick example using the date you say don't work

{
    const start = new Date(2022, 6, 1);
    const end = addMonths(start, 1);
    console.log(`start ${start} add 1 months= ${end}`);
}
{
    const start = new Date(2023, 1, 15);
    const end = addMonths(start, 1);
    console.log(`start ${start} add 1 months= ${end}`);
}
{
    const start = new Date(2023, 1, 1);
    const end = addMonths(start, 1);
    console.log(`start ${start} add 1 months= ${end}`);
}

shows

start Fri Jul 01 2022 00:00:00 GMT 0100 (British Summer Time) add 1 months= Mon Aug 01 2022 00:00:00 GMT 0100 (British Summer Time)
start Wed Feb 15 2023 00:00:00 GMT 0000 (Greenwich Mean Time) add 1 months= Wed Mar 15 2023 00:00:00 GMT 0000 (Greenwich Mean Time)
start Wed Feb 01 2023 00:00:00 GMT 0000 (Greenwich Mean Time) add 1 months= Wed Mar 01 2023 00:00:00 GMT 0000 (Greenwich Mean Time)

so all working as expected

  • Related