Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Date of an existing moment.js object

Let's say I have an existing moment object:

var m = moment(); // this will default to now 

and want to update it with a new Date object, but WITHOUT REPLACING the entire object. E.g. this is NOT an acceptable solution for me:

m = moment(new Date()); 

The only solution I can find in there docs, is using set method:

m.set({'year': 2013, 'month': 3}); 

but in this way we'll need to split our existing Date object into peaces like this:

var myDate = new Date(); var newDate = moment(myDate);  var splittedDate = {     year: newDate.get('year'),     month: newDate.get('month'),     date: newDate.get('date'),     hour: newDate.get('hour'),     minute: newDate.get('minute'),     second: newDate.get('second'),     millisecond: newDate.get('millisecond') };  m.set(splittedDate); 

But this looks ugly to me. Maybe someone can suggest a better solution?

like image 897
Eduard Ghazanchyan Avatar asked Mar 11 '15 08:03

Eduard Ghazanchyan


People also ask

How do I change a moment date to a specific format?

Date Formatting Date format conversion with Moment is simple, as shown in the following example. moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format.

How do you make a moment date?

Creating a moment object with a specific date and time is possible by calling the moment() function with arguments. Like the JavaScript Date, a moment object can be created from the number of milliseconds since 1970/1/1. Another possibility is using an array [year, month, day, hour, minute, second, milliseconds] .

How do I change the time on my moment?

To change time with moment. js and JavaScript, we can use the set method. to create a moment object from a date string with moment . Then we call set on the returned moment object with an object that sets the hour h and minute m .


1 Answers

It may be a little late, but you can transform your new date to an object (newDate.toObject()) and pass it to the set method of your previous moment object:

var m = moment(); // Initial moment object  // Create the new date var myDate = new Date(); var newDate = moment(myDate);  // Inject it into the initial moment object m.set(newDate.toObject()); 
like image 66
Arnaud Avatar answered Oct 20 '22 04:10

Arnaud