Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  186] [ 4]  / answers: 1 / hits: 84356  / 9 Years ago, wed, march 11, 2015, 12:00:00

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?


More From » momentjs

 Answers
4

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

[#67487] Monday, March 9, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annalieset

Total Points: 733
Total Questions: 92
Total Answers: 109

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
;