简体   繁体   中英

How to get date object from moment.js after formatting it

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 ?

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.

Using the date object with moment clones it and the original object is left intact to continue to use. But to convert it back just pass the formatted moment string into a new date object.

var myDateObj = new Date(2011, 9, 16);
var now = moment(myDateObj);
#Now convert it back to date object
var newDateObj = new Date(now.format("YYYY-MM-DDTHH:mm:ssZ"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM