我有一个输入字段,用户可以在其中输入以下内容:
Datetime: DD-MMM-YY HH:mm:ss.SSS
Date: DD-MMM-YY
Time: HH:mm:ss
我正在尝试确定用户输入了上述 3 个中的哪一个,例如:
var timeInput = $scope.userDatetime;
var timeOnly = moment(timeInput, "HH:mm:ss").isValid();
上面可以告诉我用户是否只输入了时间,但是我可以确定他们是否只输入了日期或日期和时间?
此外,查看当前文档,我可以看到上面的内容可以修改为:
var timeOnly = moment(timeInput, "HH:mm:ss", true).isValid();
最佳答案
由于您的输入可以有不同的格式,因此您可以使用moment parsing with multiple formats 。正如文档所说:
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 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()
获取使用的格式。
这里是一个简单的使用示例:
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>
关于javascript - 检测用户是否输入了日期、时间或日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42024241/