解析只有DateJS的时间字符串 [英] Parse ONLY a time string with DateJS
问题描述
我正在使用优秀的(但较大的) DateJS 库来处理我的webapp中的日期和时间。我刚刚遇到了一些我不知道如何处理的东西。
I'm using the excellent (but large) DateJS library to handle dates and times in my webapp. I just came across something that I'm not sure how to handle.
我希望我的用户只能输入时间字符串,而不用日期,但应该能够以任何方式输入。例如:
I want my users to be able to enter Time strings only, without a date, but they should be able to enter it in any manner they please. For instance:
- 5:00 pm
- 17:00
- 5:00 pm
- 5:00p
- 5p
- 等。
- 5:00 pm
- 17:00
- 5:00pm
- 5:00p
- 5p
- etc.
使用 Date.parse(value)
将这些字符串转换为完整日期,我想要的是。但是,它也允许用户输入日期字符串的任何其他部分,例如:
Using Date.parse(value)
converts these strings into a full date, which is exactly what I want. However, it also allows the user to enter any other part of a date string, such as:
- sat 5pm
- 1/1/2010 5pm
- 等。
尝试使用DateJS验证时间值的输入字段。一些东西:
I'm trying to use DateJS to validate an input field for a time value. Something like:
function validateTime(value) {
return Date.parse(value) !== null;
}
有没有办法使用DateJS功能来解决这个问题?还有其他 SO问题提供解决方案,但是如果DateJS有办法做到这一点,我真的不想在我的应用程序中添加更多的自定义代码来执行此操作。
Is there a way to use DateJS features to solve this? There are other SO questions that provide solutions, but if DateJS has a way to do this, I don't really want to add more custom code to my app to do this.
推荐答案
在提出问题后不久,我发现Date.parseExact()可以使用一个格式字符串数组。不知怎的,我错过了我设法使用以下代码:
Shortly after asking my question, I discovered that Date.parseExact() can take an array of format strings. Somehow I'm missed that. I managed to get something working with the following code:
function validateTime(input) {
return Date.parseExact(input, [
"H:m",
"h:mt",
"h:m t",
"ht","h t"]) != null ||
Date.parseExact(input, [
"h:mtt",
"h:m tt",
"htt","h tt"]) != null;
};
请注意,某些格式似乎无法同时包含在一起,是为什么我将它们分成两个单独的parseExact()调用。在这种情况下,我不能包含包含单个 t
的任何字符串,其格式字符串包含双重 tt
中。
Note that some formats don't seem to be able to be included together at the same time, which is why I split them into two separate parseExact() calls. In this case, I couldn't include any string that contained a single t
in it with format strings that contained a double tt
in it.
这篇关于解析只有DateJS的时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!