在角度材质中使用md-datepicker指令时,日期格式似乎不适用于直接输入。
如果我在日历中选择日期,它将按指定显示(在我的情况下为DD-MM-YYYY)但如果我尝试手动更改输入,则我的输入将被分析为MM-DD-YYYY。 / p>
到目前为止,我的日期选择器是使用this question
中的代码设置的angular.module('MyApp').config(function($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return date ? moment(date).format('DD-MM-YYYY') : '';
};
});
Here是一个可以看到问题的代码。
有没有办法设置输入格式?
答案 0 :(得分:19)
格式化日期事件是不够的。您还应该配置解析日期事件。
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'DD-MM-YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
答案 1 :(得分:5)
完整的解决方案基于:
$mdDateLocaleProvider.formatDate = function(date) {
return date ? moment(date).format('DD-MM-YYYY') : '';
};
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'DD-MM-YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
答案 2 :(得分:0)
config($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
if(date !== null) {
if(date.getMonthName == undefined) {
date.getMonthName = function() {
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
return monthNames[this.getMonth()];
}
}
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return day + ' ' + date.getMonthName() + ' ' + year;
}
};
}
答案 3 :(得分:0)
除了 formatDate -
外,还需要提供两个定义。parseDate -确保手动输入的日期有效
isDateComplete -确保不会开始验证部分输入的日期
/**
* @param date {Date}
* @returns {string} string representation of the provided date
*/
$mdDateLocaleProvider.formatDate = function (date) {
return date ? moment(date).format('DD-MM-YYYY') : '';
};
/**
* @param dateString {string} string that can be converted to a Date
* @returns {Date} JavaScript Date object created from the provided dateString
*/
$mdDateLocaleProvider.parseDate = function (dateString) {
var m = moment(dateString, 'DD-MM-YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
/**
* Check if the date string is complete enough to parse. This avoids calls to parseDate
* when the user has only typed in the first digit or two of the date.
* Allow only a day and month to be specified.
* @param dateString {string} date string to evaluate for parsing
* @returns {boolean} true if the date string is complete enough to be parsed
*/
$mdDateLocaleProvider.isDateComplete = function (dateString) {
dateString = dateString.trim();
// Look for two chunks of content (either numbers or text) separated by delimiters.
var re = /^(([a-zA-Z]{3,}|[0-9]{1,4})([ .,]+|[/-]))([a-zA-Z]{3,}|[0-9]{1,4})/;
return re.test(dateString);
};