3

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.

xunux
  • 1,531
  • 5
  • 20
  • 33
  • ISO 8601 format dates are parsed as UTC, so depending on your timezone offset '2021-03-02' might be late evening the previous day locally or early morning of the same day. – RobG Mar 23 '21 at 02:46
  • how can i get around that? it is so annoying, i want to be able to just add one month arbitrarily to 2021-03-01 but it alwaysuses my local time zone, i thought UTC would work around the local time zone since im specifcally providing the ISO with time 00:00Z , yet the add function seems to modify that and just treats it like a local thing but i dont want that at all. I had to do a work around with getUTCmonth and add a month manually – xunux Mar 24 '21 at 22:47
  • If you want YYYY-MM-DD to be parsed as local, do it yourself or use a library (overkill): `let [Y,M,D] = '2021-03-02'.split('-'); new Date(Y, M-1, D)`. You can now do everything as local. Note there are issues with adding a month, see [*Adding months to a Date in JavaScript*](https://stackoverflow.com/questions/12793045/adding-months-to-a-date-in-javascript/12793246?r=SearchResults&s=1|71.7373#12793246). – RobG Mar 24 '21 at 23:03
  • no i dont want it to use my local time zone at all, i want it to ignore time zones completely, the issue im having with date-fns is the add function and even the format function, if given a date that looks like `2021-03-01T00:00:00.000Z` since im -6h locally, when i format it it modifies the time and i get a date that is BEFORE that date, which defeats the whole purpose. If i say here is my date `2021-03-01T00:00:00.000Z` now format it like yyyy-MM dont frikkin change the date by adding local time stuff – xunux Mar 24 '21 at 23:14

0 Answers0