当尝试为日期选择器定义多种输入日期格式时,我们似乎遇到了只能定义一种格式的问题。如果不满足此格式,则默认为美国日期格式 (MM/dd/YYYY)。
例如,如果我们将格式设置为 dd-MM-yyyy,但输入日期为 7/8/09,则这将被解释为 2009 年 7 月 8 日。
有没有一种方法可以接受和验证多种日期格式,例如:
'dd-MM-yyyy',
'dd.MM.yyyy',
'dd/MM/yyyy',
'dd-MM-yy',
'dd.MM.yy',
'dd/MM/yy,
'd/M/yy'
最佳答案
您可以在将值附加到日期选择器之前使用解析器解析该值
csapp.directive("csDateConverter", function () {
var linkFunction = function (scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$parsers.push(function (datepickerValue) {
//convert the date as per your specified format
var date = moment(datepickerValue, scope.format)
//convert it to the format recognized by datepicker
return date.format("YYYY-MM-DD");
});
};
return {
scope: {format: '='}
restrict: "A",
require: "ngModel",
link: linkFunction
};
});
你可以像这样使用它
<datepicker ng-model="dt" cs-date-converter="yyyy.mm.dd"></datepicker>
根据评论进行编辑
删除了隔离范围并将scope.format更改为attrs.format
csapp.directive("csDateConverter", function () {
var linkFunction = function (scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$parsers.push(function (datepickerValue) {
//convert the date as per your specified format
var date = moment(datepickerValue, attrs.format.toUpperCase())
//convert it to the format recognized by datepicker
return date.format("YYYY-MM-DD");
});
};
return {
restrict: "A",
require: "ngModel",
link: linkFunction
};
});
关于angularjs - Angular Bootstrap 日期选择器多种格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24870750/