Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment.js add/subtract days without affecting the original date

Tags:

momentjs

How do you add or subtract days to a default date using moment.js?

I am trying to get the start and end dates of the week like below:

const current = moment.tz('2016-03-04', 'America/Los_Angeles'); const startOfWeek = current.startOf('isoWeek').weekday(0); const endOfWeek = current.endOf('isoWeek').weekday(6); 

When calling endOfWeek, I am getting the expected value. However, my problem is that startOfWeek is overridden by the endOfWeek value.

I wanted to get the value of both startOfWeek and endOfWeek

like image 340
rniocena Avatar asked Mar 04 '16 05:03

rniocena


People also ask

How do you subtract days from moments?

Your code, then, should look like: var startdate = moment(); startdate = startdate. subtract(1, "days"); startdate = startdate. format("DD-MM-YYYY");

How do you add days to moments with dates?

To add time, pass the key of what time you want to add, and the amount you want to add. moment(). add(7, 'days');

How do you add 30 days in a moment?

moment(). add(30, 'days');

What is _D and _I in moment?

_i can also be undefined, in the case of creating the current moment with moment() . _d is the instance of the Date object that backs the moment object. If you are in "local mode", then _d will have the same local date and time as the moment object exhibits with the public API.


2 Answers

You just need to clone the moment first before modifying it. Use either current.clone().whatever... or moment(current).whatever.... They both do the same thing.

This is necessary because moments are mutable.

like image 130
Matt Johnson-Pint Avatar answered Sep 28 '22 10:09

Matt Johnson-Pint


You need to clone the value of current and then perform the operations:

const current = moment.tz('2016-03-04', 'America/Los_Angeles'); const startOfWeek = current.clone().startOf('isoWeek').weekday(0); const endOfWeek = current.endOf('isoWeek').weekday(6); 
like image 25
Dixita Avatar answered Sep 28 '22 08:09

Dixita