更新时间:2023-11-28 14:53:16
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使用一些简单的试探法来确定要使用的格式.顺序:
Moment uses some simple heuristics to determine which format to use. In order:
此外,您可以使用 creationData()
来获取使用的格式
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>