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

编程入门 行业动态 更新时间:2024-10-08 00:32:15
本文介绍了检测用户是否输入了日期,时间或日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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="ajax.googleapis/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="cdnjs.cloudflare/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>

更多推荐

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

本文发布于:2023-11-28 08:15:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641627.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   时间   用户

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!