javascript - 检测用户是否输入了日期、时间或日期时间

标签 javascript momentjs datetime-format

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

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/

相关文章:

javascript - 为什么我收到错误 "Too much recursion"?

javascript - 检查弹出窗口是否以电话友好的方式关闭(检查 .closed 的值不起作用)

javascript - 如何比较javascript中的两个日期时间?

java - 将时间转换为UTC时间是相反的方式

c# - 如何在 C# 中将日期(从日期时间输入字段)转换为另一种日期格式?

php - Facebook PHP SDK - 需要在特定帐户上登录

javascript - 相同的 RegExp 交替返回 true 和 false。为什么?

javascript - Angular Date 管道,以及一个带有 Momentjs 的简单计时器

javascript - Moment.js 你如何获得当前季度和前三个季度以及年份?

javascript - moment.js 将东部夏令时间转换为 UTC?