rniocena
rniocena

Reputation: 1125

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

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

Upvotes: 48

Views: 14287

Answers (3)

Dixita
Dixita

Reputation: 101

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);

Upvotes: 8

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241525

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.

Upvotes: 67

rniocena
rniocena

Reputation: 1125

Solved the problem by getting the format of the startOfWeek and saving it in a variable. Then from the new variable, I convert it to a moment instance and from here, I get the endOfWeek value.

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

const startOfWeekConvert = startOfWeek.format('YYYY-MM-DD');

const endOfWeek = startOfWeekConvert.endOf('isoWeek').weekday(6);

I am now able to get both the start and end dates of the week at the same time.

Upvotes: -1

Related Questions