检测用户是否输入了日期,时间或日期时间 [英] Detecting if user has entered date, time or datetime

查看:89
本文介绍了检测用户是否输入了日期,时间或日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段,用户可以在其中输入以下内容:

I have an input field in which users can either enter the following:

Datetime: DD-MMM-YY HH:mm:ss.SSS
Date:     DD-MMM-YY
Time:     HH:mm:ss

我正在尝试确定用户输入的以上3个中的哪个,例如:

I am trying to determine which of the above 3 a user has entered, for example:

var timeInput = $scope.userDatetime;
var timeOnly = moment(timeInput, "HH:mm:ss").isValid();

以上内容可以告诉我用户是否仅输入时间,但是我可以确定他们是否仅输入日期或日期和时间吗?

The above can tell me if a user has entered a time only, but can i determine if they have entered a date only or date and time?

另外,看看文档,我可以看到上面的内容可以修改为:

Additionally, looking at the moment docs, i can see the above can be modified to:

var timeOnly = moment(timeInput, "HH:mm:ss", true).isValid();

推荐答案

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

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>

这篇关于检测用户是否输入了日期,时间或日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆