字符串值的問題將被解析。 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值直接來自服務器響應。 –