Javascript 格式化后如何从moment.js获取日期对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38384263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get date object from moment.js after formatting it
提问by ATHER
Using typescript, I am formatting my date with moment.js like this.
使用打字稿,我像这样用 moment.js 格式化我的日期。
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 ?
format 方法返回一个字符串,如何将其转换回日期对象?
回答by Ajay Kumar Meher
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/
https://momentjs.com/guides/#/lib-concepts/internal-properties/
To retrieve a native Date object from Moment, use .toDate()
To retrieve a native Date object from Moment, use .toDate()
You can directly get the Date object from Moment.
您可以直接从 Moment 获取 Date 对象。
回答by DasSwede
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.
使用带有 moment 的 date 对象克隆它,原始对象保持不变以继续使用。但是要将其转换回来,只需将格式化的时刻字符串传递给新的日期对象。
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"));