How to find format (not validate against a particular format) of date with moment.js

北慕城南 提交于 2019-12-13 03:17:12

问题


I have a given Date string, which is already formatted by moment.js by someone. I want to get that format.

I have checked existing questions and came across this one - check format of date with moment.js

The solution provided is not returning the format of the date. Rather it is validating against some given formats.

I want a function getMomentDateFormat like this -

var dateString = field.value; //"Nov 30, 2017"
var dateFormat = getMomentDateFormat(dateString ); //I want dateFormat = "MMM DD, YYYY"

回答1:


You can use Parse Date Format plug-in:

This plugin extracts the format of a date/time string.

Here an example (anyway it returns MMM D, YYYY instead of MMM DD, YYYY):

function getMomentDateFormat(input){
  return moment.parseFormat(input);
}

var field = { value: "Nov 30, 2017" };
var dateString = field.value; //"Nov 30, 2017"
var dateFormat = getMomentDateFormat(dateString);

console.log(dateFormat);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
<script src="https://gr2m.github.io/moment-parseformat/moment-parseformat.js"></script>

PS. Do not use scripts directly from https://gr2m.github.io/, refer github repo.



来源:https://stackoverflow.com/questions/47567930/how-to-find-format-not-validate-against-a-particular-format-of-date-with-momen

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