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
Your code, then, should look like: var startdate = moment(); startdate = startdate. subtract(1, "days"); startdate = startdate. format("DD-MM-YYYY");
To add time, pass the key of what time you want to add, and the amount you want to add. moment(). add(7, 'days');
moment(). add(30, 'days');
_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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With