When trying to define more than one input date format for Date Picker we seem to have an issue where only one format can be defined. If this format is not met it defaults to americanised date format (MM/dd/YYYY).
For example if we set the format to dd-MM-yyyy but enter the date as 7/8/09, this is interpreted as the 8th of July 2009.
Is there a way of accepting and validating more than one date format, such as:
'dd-MM-yyyy',
'dd.MM.yyyy',
'dd/MM/yyyy',
'dd-MM-yy',
'dd.MM.yy',
'dd/MM/yy,
'd/M/yy'
you can use parser to parse the value before it being attached to datepicker
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
};
});
and you can use it like this
<datepicker ng-model="dt" cs-date-converter="yyyy.mm.dd"></datepicker>
EDIT as per comments
removed isolate scope & changed scope.format to 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
};
});