且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测用户是否输入了日期,时间或日期时间

更新时间:2023-11-28 14:53:16

由于您的输入可以具有不同的格式,因此可以使用

Since your input can have different formats, you can use moment parsing with multiple formats. As the docs says:

如果您不知道输入字符串的确切格式,但是知道它可能是多种格式之一,则可以使用一系列格式.

If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.

这与字符串+格式相同,只有它会尝试将输入匹配为多种格式.

This is the same as String + Format, only it will try to match the input to multiple formats.

Moment使用一些简单的试探法来确定要使用的格式.顺序:

Moment uses some simple heuristics to determine which format to use. In order:

  • 首选格式会导致有效日期超过无效日期.
  • 首选格式多于少的字符串,而格式多于少的字符串,即,首选更严格的解析.
  • 在数组中优先使用格式晚于
  • Prefer formats resulting in valid dates over invalid ones.
  • Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.
  • Prefer formats earlier in the array than later

此外,您可以使用 creationData() 来获取使用的格式

Moreover you can use creationData() to get the format used.

下面是一个简单的使用示例:

Here a simple example of use:

function getFormatInserted(value){
  var mom = moment(value, ["HH:mm:ss", 'DD-MMM-YY HH:mm:ss.SSS', 'DD-MMM-YY'], true);
  if( mom.isValid() ){
    return mom.creationData().format;
  }
  return '';
}

$('#btn').click(function(){
  var value = $('#date').val();
  var format = getFormatInserted(value);
  $('#result').html(format);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

<input type="text" id="date">
<button type="button" id="btn">Get format</button>
<span id="result"></span>