Detecting if user has entered date, time or datetime

别说谁变了你拦得住时间么 提交于 2019-12-11 04:56:00

问题


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

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();

回答1:


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 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

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="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>


来源:https://stackoverflow.com/questions/42024241/detecting-if-user-has-entered-date-time-or-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!