Search code examples
javascriptdatemethod-chaining

Is there a way to set date and month on a date object in a single statement?


I'm trying to calculate a date based on another date by adding a certain period of time. Let's say if I want to add 3 months to a date, then the new date should be one day before the date after 3 months. Taking that example, below is the code that I came closest to for achieving what I want to do:

new Date(
    date
        .setMonth(date.getMonth() + 3)
        .setDate(date.getDate() - 1)
)

But this returns an error: TypeError: date.setMonth(...).setDate is not a function. I think the chaining of methods is not working, so I'll probably have to setDate in the next statement. Is there a way to do this in a single statement of code?


Solution

  • Is there a way to set date and month on a date object in a single statement?

    Yes. The following sets the month to January and the day to the first on one statement:

    let d = new Date();
    d.setMonth(0, 1);
    

    …if I want to add 3 months to a date, then the new date should be one day before the date after 3 months

    No, you can't do that in one statement because adding a month needs to consider the number of days in the month. E.g. adding one month to 31 Jan 2020 results in 31 Feb, and since there were only 29 days in Feb 2020, the date is set to 2 Mar 2020. Similarly, adding 1 month to 31 May gives 31 Jun which rolls over to 1 Jul. So you need to add months first (see Adding months to a Date in JavaScript), then subtract one day (see Add days to JavaScript Date).