Using typescript, I am formatting my date with moment.js like this.
function getCreatedDate(objContainingDate: any): Date {
// Following line does not work since it is returning string,
// I need formatted date object to return
return moment(objContainingDate.createdDate).format("L")
}
The format method returns a string, how to convert it back to date object ?
toDate() Method. The moment(). toDate() method is used to return the Moment object as a native JavaScript object. This Date object can then be used with the native Date methods or for support in other libraries.
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.
Create an input for the date and button to submit. Now use the moment() method to convert the date into a moment object. Use the format() method to change the format of the date, following is the syntax for changing the format of the date to 'DD-MM-YYYY'.
moment('24/12/2019 09:15:00', "DD MM YYYY hh:mm:ss"); You can use strict mode, which will identify the parsing error and set the Moment object as invalid: moment('24/12/2019 09:15:00', "DD MM YYYY hh:mm:ss", true); The parsing tokens are similar to the formatting tokens used in moment#format .
This might be a delayed response.But, I think it can help others who still needs an answer.
https://momentjs.com/guides/#/lib-concepts/internal-properties/
To retrieve a native Date object from Moment, use .toDate()
You can directly get the Date object from Moment.
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