Search code examples
javascriptangulardatetimemomentjsutc

Add and subtract 3 month from a given date time


I have this start date : 2023-09-03T00:00:00+05:30 and end date : 2023-09-10T00:00:00+05:30

I want to subtract 90 days from start date and add 90 days from end date

and then convert it to UTC format

for that I was using this function in angular

moment(startStr, 'YYYY-MM-DD hh:mm:ss').utc().format('YYYY-MM-DD hh:mm:ss');
moment(endStr, 'YYYY-MM-DD hh:mm:ss').utc().format('YYYY-MM-DD hh:mm:ss');

How can I do that?


Solution

  • For moment you can use add and substract functions. Example below:

    var startDate = moment(startStr, 'YYYY-MM-DD hh:mm:ss');
    var endDate = moment(endStr, 'YYYY-MM-DD hh:mm:ss');
    
    startDate =  startDate.subtract(90, 'days');
    console.log(startDate);
    endDate =  endDate.add(90, 'days');
    console.log(endDate);
    
    // then do your utc conversion
    

    Reference material:

    moment add function link

    moment subsctract function link