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?
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.
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] .
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 .
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With