我有一个输入字段,用户可以在其中输入以下内容:
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>
更多推荐
检测用户是否输入了日期,时间或日期时间
发布评论