WoJ
WoJ

Reputation: 30035

How to deal with mutations of a fixed date?

The .add() method of moment.js

Mutates the original moment by adding time.

var now = moment([2015, 11, 29, 14]);
var tomorrow = now.add(1, 'd');
// now has changed

What is the correct approach if I have a fixed 'now' moment which I would like to reuse later in my program?

The best I found is a construction like

var ref = [2015, 11, 29, 14];
var now = moment(ref);
var tomorrow = moment(ref).add(1, 'd');
var start = moment(ref).startOf('day'); // beginning of today
var end = moment(ref).add(1, 'd').endOf('day'); // end of tomorrow

but it looks clumsy to me.

Upvotes: 1

Views: 148

Answers (1)

NanoWizard
NanoWizard

Reputation: 2164

From their docs:

Note: It should be noted that moments are mutable. Calling any of the manipulation methods will change the original moment.

If you want to create a copy and manipulate it, you should use moment#clone before manipulating the moment. More info on cloning.

var now = moment([2015, 11, 29, 14]);
var tomorrow = now.clone().add(1, 'd');
var start = now.clone().startOf('day'); // beginning of today
var end = now.clone().add(1, 'd').endOf('day'); // end of tomorrow

A quick look at their code on Github shows that all they do there is return new Moment(this), so you could do the same thing by doing new Moment(now) instead of now.clone() if that's more clear to you. I personally think you should use whatever method seems the most clear to you.

Upvotes: 1

Related Questions