字符串值的问题将被解析。 2016年5月10日和2016年10月5日可能会混淆。 2016-05-10或2016-10-05。日期对象可以防止这种情况发生。你不能使用已定义的过滤器将字符串数据转换为日期对象吗?
我很快修改了一些日期过滤器中的代码,我使用的是Angular 1.x,它使用YYYYMMDD(20160516)的数字日期格式。
/**
* @name yourDate
* @ngdoc filter
* @requires $filter
* @param DateValue {string} Date Value (YYYY-MM-DD)
* @returns Date Filter with the Date Object
* @description
* Convert date from the format YYYY-MM-DD to the proper date object for future use by other objects/filters
*/
angular.module('myApp').filter('yourDate', function($filter) {
var DateFilter = $filter('date');
return function(DateValue) {
var Input = "";
var ResultData = DateValue;
if (! ((DateValue === null) || (typeof DateValue == 'undefined'))) {
if (Input.length == 10) {
var Year = parseInt(Input.substr(0,4));
var Month = parseInt(Input.substr(5,2)) - 1;
var Day = parseInt(Input.substr(8, 2));
var DateObject = new Date(Year, Month, Day);
ResultData = DateFilter(DateObject); // Return Input to the original filter (date)
} else {
}
} else {
}
return ResultData;
};
}
);
/**
* @description
* Work with dates to convert from and to the YYYY-MM-DD format that is stored in the system.
*/
angular.module('myApp').directive('yourDate',
function($filter) {
return {
restrict: 'A',
require: '^ngModel',
link: function($scope, element, attrs, ngModelControl) {
var slsDateFilter = $filter('yourDate');
ngModelControl.$formatters.push(function(value) {
return slsDateFilter(value);
});
ngModelControl.$parsers.push(function(value) {
var DateObject = new Date(value); // Convert from Date to YYYY-MM-DD
return DateObject.getFullYear().toString() + '-' + DateObject.getMonth().toString() + '-' + DateObject.getDate().toString();
});
}
};
}
);
此代码仅使用标准的Angular Filter选项,因此您应该可以将其与Material date选取器结合使用。
对不起,如果我的问题不清楚。我的意思是标准的HTML日期选择器接受规范化的日期格式YYYY-MM-DD例如 '' 它非常容易绑定到它JSON/AJAX值直接来自服务器响应。 –