Function to get the input provided to momentjs

こ雲淡風輕ζ 提交于 2019-12-30 10:44:26

问题


Is there any function to get the input that was provided to moment()

In the example below, inputDate becomes null.

var date = moment("invalid date");
if(!data.isValid()){
  return { message: "Invalid date", inputDate: date }
}

I can access the input using internals i.e. date._i but was wondering if there's any function that would return the input provided to moment constructor.


回答1:


You can use creationData()

After a moment object is created, all of the inputs can be accessed with creationData() method:

moment("2013-01-02", "YYYY-MM-DD", true).creationData() === {
    input: "2013-01-02",
    format: "YYYY-MM-DD",
    locale: Locale obj,
    isUTC: false,
    strict: true
}

Here a live example:

var date = moment("invalid date", moment.ISO_8601);
console.log(date.creationData().input);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>

As a side note:

  • I've used moment.ISO_8601 in my snippet to prevent Deprecation Warning, as shown here.
  • Something quite similar was asked (but not a duplicate) was asked here.


来源:https://stackoverflow.com/questions/47907053/function-to-get-the-input-provided-to-momentjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!