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