'bug when adding a month with date-fns add() method?

I've been trying to add just one month to a date using date-fns add() function. It works as advertised most of the time.

 period = new Date('2021-03-01') //im actually getting this from a DB, already in date format
 console.log(period) //logs 2021-03-01T00:00:00.000Z just as it looks in DB
 add(period, {months: 1})
 //returns 2021-03-29T00:00:00.000Z
 // which is clearly not the first day of the next month

If i provide a date that is not the first day of the month, it returns just fine

 period = new Date('2021-03-02')
 add(period, {months: 1})
 //returns 2021-04-02T00:00:00.000Z

This has been driving me crazy for hours and i had to build my own function to add a month to my date, using Date.getUTC methods. Does anybody know if this is an actual bug, a feature? am i doing something wrong?

I thought it might have something to do with my local time zone, since the newer versions of date-fns dont use universal time zone anymore. However, it's not like it's giving me the last day of the month which would be march 31, it gives me the 29th... which just seems arbitrary.



Solution 1:[1]

I think that's too late to answer but I found the solution to this, just to applying substring function to the ISO string date to remove the time part that you going to use in add months functions.

Ej.

 import { add } from 'date-fns'
 const date = '2022-04-030T00:00:00.000Z'
 const dateWithouIsoFormat = `${date.substring(0, 10)} 00:00:00.000`
 const dateToAddMonths = new Date(dateWithouIsoFormat)
 const dateWithMonth = add(dateToAddMonths , { months: 1 })

It's not the cleanest way to solve this, but it works!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1