date-utils icon indicating copy to clipboard operation
date-utils copied to clipboard

Function add/addMonths compute error

Open ikarosu opened this issue 5 years ago • 3 comments

new Date().addMonths(0)
Fri May 31 2019 17:07:50 GMT+0800 (China Standard Time)
new Date().addMonths(1)
Mon Jul 01 2019 17:07:58 GMT+0800 (China Standard Time)
new Date().addMonths(2)
Wed Jul 31 2019 17:08:01 GMT+0800 (China Standard Time)
new Date().addMonths(3)
Sat Aug 31 2019 17:08:03 GMT+0800 (China Standard Time)
new Date().add({ months: 0 })
Fri May 31 2019 17:08:24 GMT+0800 (China Standard Time)
new Date().add({ months: 1 })
Mon Jul 01 2019 17:08:27 GMT+0800 (China Standard Time)
new Date().add({ months: 2 })
Wed Jul 31 2019 17:08:29 GMT+0800 (China Standard Time)
new Date().add({ months: 3 })
Sat Aug 31 2019 17:08:32 GMT+0800 (China Standard Time)

ikarosu avatar May 31 '19 09:05 ikarosu

When the date is 31,and calling the setMonths() method.If there are no 31 days this months,then will get the 1st of the next month.

ikarosu avatar May 31 '19 10:05 ikarosu

add and addMonths use Date.setMonth:

new Date(new Date().setMonth(5))

JerrySievert avatar May 31 '19 18:05 JerrySievert

Yeah,I know.But we can avoid this problem like this:

const d = new Date()
d.setDate(1)
new Date(d.clone().setMonth(d.getMonth() + i))

ikarosu avatar Jul 10 '19 07:07 ikarosu