How to set the date of an existing moment.js object with JavaScript?

Sometimes, we want to set the date of an existing moment.js object with JavaScript.

In this article, we’ll look at how to set the date of an existing moment.js object with JavaScript.

How to set the date of an existing moment.js object with JavaScript?

To set the date of an existing moment.js object with JavaScript, we can use the set method.

For instance, we write:

const m = moment();
const myDate = new Date();
const newDate = moment(myDate);
m.set(newDate.toObject());
console.log(m)

We call moment to create a moment object.

Then we create the newDate moment object with the current date and time.

Next, we call newDate.toObject to return the date and time data in an object.

Finally, we call m.set with the returned object to set the new date and time to the same date and time as newDate.

Conclusion

To set the date of an existing moment.js object with JavaScript, we can use the set method.