'Clone moment js object
I have momentjs object in state
state = {
startDate: getNow() //this funtion return a momemtJS object
}
in one function, I need to get the date one year before startDate
const dateBeforeOneYear = this.state.startDate.subtract(1, 'years');
But if I do like this, I modify the state by mistake
So I try to copy the state
const copyStartDate = {...this.state.startDate}
const copyStartDate = this.state.startDate.subtract(1, 'years');
But now I get the error, substract is not a function, I guess because copyStartDate is no more MomemntJs
Solution 1:[1]
There's a method to clone a moment object:
const yearBefore = this.state.startDate.clone().subtract(1, 'years');
It would also be a better idea to store a serialisable representation of the date in your component state, such as the result of calling .valueOf() on either a Date or a Moment, either of which returns the number of milliseconds since the UNIX epoch.
Solution 2:[2]
moment.js has its own api for cloning moment object.
var copy = momentObj.clone();
And I agree on storing dates serialize representation instead of Object in store.
Solution 3:[3]
It's also possible to copy a moment object through it's constructor. Like so
const firstMoment = moment("2020-08-18");
const clone = moment(firstMoment);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Penny Liu |
| Solution 3 | JayCodist |
