Javascript 使用 momentjs 更改 Angular Material 中 md-datepicker 的格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32566416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change format of md-datepicker in Angular Material with momentjs
提问by dearn44
Angular material introduced a new date picker component found here.
Angular material 引入了一个新的日期选择器组件,可在此处找到。
I want the date returned by this component to be in the format yyy-mm-ddbut I am not sure how is this done. By searching I found that $mdDateLocaleProvider
can be used, but I could not find an example of using it.
我希望此组件返回的日期采用yyy-mm-dd格式,但我不确定这是如何完成的。通过搜索我发现$mdDateLocaleProvider
可以使用,但我找不到使用它的示例。
Can someone show me a working example of formatting the date returned by md-datepicker
?
有人可以向我展示一个格式化返回日期的工作示例md-datepicker
吗?
回答by Bohuslav Burghardt
There is a documentation for $mdDateLocaleProvider
in the Angular Material docs.
$mdDateLocaleProvider
在 Angular Material 文档中有一个文档。
angular.module('app').config(function($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('YYYY-MM-DD');
};
});
If you don't use moment.js, substitute the code inside formatDate
for whatever you wish to use to format the date.
如果您不使用 moment.js,请将里面的代码替换formatDate
为您希望用于格式化日期的任何内容。
Hereis a CodePen example based on the samples from Angular Material docs.
这是一个基于 Angular Material 文档示例的 CodePen 示例。
回答by shulito
To also address the problem pointed out by kazuar:
还要解决 kazuar 指出的问题:
Unfortunately it doesn't work if the date is typed from the keyboard
不幸的是,如果日期是从键盘输入的,则它不起作用
you should define the parseDate method as well. From the docs:
您还应该定义 parseDate 方法。从文档:
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'L', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
For a full example, I have in my app (using moment):
对于一个完整的例子,我在我的应用程序中有(使用 moment):
$mdDateLocaleProvider.formatDate = function(date) {
return 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);
};
Regards
问候
回答by Ben Taliadoros
For those not using Moment.js, you can format as a string:
对于那些不使用 Moment.js 的人,您可以格式化为字符串:
.config(function($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return day + '/' + (monthIndex + 1) + '/' + year;
};
});
回答by Janderson Silva
Worked perfectly when the date is typed from the keyborard and returned null in initiation to avoid the massage 'Invalid date' in md-datapicker directive:
当从键盘输入日期并在启动时返回 null 以避免在 md-datapicker 指令中按摩“无效日期”时,效果很好:
$mdDateLocaleProvider.formatDate = function(date) {
return date ? moment(date).format('DD/MM/YYYY') : null;
};
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'DD/MM/YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
回答by Christiaan Westerbeek
Changing date format, month names and week names during runtime is perfectly possible with AngularJS 1.5.9 and moment 2.17.1.
AngularJS 1.5.9 和 moment 2.17.1 完全可以在运行时更改日期格式、月份名称和周名称。
First configure the initial language. (In this example the configuration of angular-translate/$translateProvider is optional.)
首先配置初始语言。(在这个例子中,angular-translate/$translateProvider 的配置是可选的。)
angular.module('app').config(configureLocalization)
configureLocalization.$inject = ['$translateProvider', '$mdDateLocaleProvider', 'localdb', '__config'];
function configureLocalization($translateProvider, $mdDateLocaleProvider, localdb, __config) {
// Configure angular-translate
$translateProvider.useStaticFilesLoader({
prefix: 'locale/',
suffix: '.json'
});
// get the language from local storage using a helper
var language = localdb.get('language');
if (!language || language === 'undefined') {
localdb.set('language', (language = __config.app.defaultLanguage));
}
// Set the preferredLanguage in angular-translate
$translateProvider.preferredLanguage(language);
// Change moment's locale so the 'L'-format is adjusted.
// For example the 'L'-format is DD.MM.YYYY for German
moment.locale(language);
// Set month and week names for the general $mdDateLocale service
var localeData = moment.localeData();
$mdDateLocaleProvider.months = localeData._months;
$mdDateLocaleProvider.shortMonths = moment.monthsShort();
$mdDateLocaleProvider.days = localeData._weekdays;
$mdDateLocaleProvider.shortDays = localeData._weekdaysMin;
// Optionaly let the week start on the day as defined by moment's locale data
$mdDateLocaleProvider.firstDayOfWeek = localeData._week.dow;
// Format and parse dates based on moment's 'L'-format
// 'L'-format may later be changed
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'L', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
$mdDateLocaleProvider.formatDate = function(date) {
var m = moment(date);
return m.isValid() ? m.format('L') : '';
};
}
Later you may have some base controller that watches a language variable which is changed when the user selects another language.
稍后您可能会有一些基本控制器来监视语言变量,当用户选择另一种语言时,该变量会发生变化。
angular.module('app').controller('BaseCtrl', Base);
Base.$inject = ['$scope', '$translate', 'localdb', '$mdDateLocale'];
function Base($scope, $translate, localdb, $mdDateLocale) {
var vm = this;
vm.language = $translate.use();
$scope.$watch('BaseCtrl.language', function(newValue, oldValue) {
// Set the new language in local storage
localdb.set('language', newValue);
$translate.use(newValue);
// Change moment's locale so the 'L'-format is adjusted.
// For example the 'L'-format is DD-MM-YYYY for Dutch
moment.locale(newValue);
// Set month and week names for the general $mdDateLocale service
var localeDate = moment.localeData();
$mdDateLocale.months = localeDate._months;
$mdDateLocale.shortMonths = moment.monthsShort();
$mdDateLocale.days = localeDate._weekdays;
$mdDateLocale.shortDays = localeDate._weekdaysMin;
// Optionaly let the week start on the day as defined by moment's locale data
$mdDateLocale.firstDayOfWeek = localeData._week.dow;
});
}
Notice how we don't need to change the $mdDateLocale.formatDate
and $mdDateLocale.parseDate
methods as they are already configured to use the 'L'-format that is changed by calling moment.locale(newValue)
.
请注意,我们不需要更改$mdDateLocale.formatDate
和$mdDateLocale.parseDate
方法,因为它们已经配置为使用通过调用更改的“L”格式moment.locale(newValue)
。
See the documentation for $mdDateLocaleProvider for more locale customization: https://material.angularjs.org/latest/api/service/$mdDateLocaleProvider
有关更多语言环境自定义,请参阅 $mdDateLocaleProvider 的文档:https: //material.angularjs.org/latest/api/service/ $mdDateLocaleProvider
Bonus: This is how the language selector may look like:
奖励:这是语言选择器的样子:
<md-select ng-model="BaseCtrl.language" class="md-no-underline">
<md-option
ng-repeat="language in ['en', 'de', 'fr', 'nl']"
ng-value ="language"
><span
class ="flag-icon flag-icon-{{language ==='en' ? 'gb' : language}}"
></span>
</md-option>
</md-select>
回答by Ravindra Vairagi
-- When we use md-DatePicker in md-dialog then $mdDateLocaleProvider service doesnot format the date as we need. We have to use $mdDateLocale in controller of md-dialog to format the date of md-DatePicker. for example -
-- 当我们在 md-dialog 中使用 md-DatePicker 时, $mdDateLocaleProvider 服务不会按照我们的需要格式化日期。我们必须在 md-dialog 的控制器中使用 $mdDateLocale 来格式化 md-DatePicker 的日期。例如 -
angular.module('MyApp').controller('AppCtrl', function($scope, $mdDateLocale) {
$mdDateLocale.formatDate = function(date) {
return moment(date).format('YYYY-MM-DD');
};
$scope.myDate = new Date('2015-10-15');
$scope.minDate = new Date();
$scope.maxDate = new Date();
});
回答by marcinowski
Using $filter
instead of moment.js
and in reference to responses from @Ian Poston Framer and @java dev for me the following finally worked for me:
使用$filter
而不是moment.js
参考@Ian Poston Framer 和@java dev 对我的回应,以下最终对我有用:
angular
.module('App', ['ngMaterial'])
.run(function($mdDateLocale, $filter) {
$mdDateLocale.formatDate = function(date) {
return $filter('date')(date, "dd-MM-yyyy");
};
})
I couldn't inject $filter
into.config
because it's not a provider, so I had to do it inside .run
with $mdDateLocale
.
我不能注入$filter
到.config
,因为它不是一个提供者,所以我不得不做这里面.run
有$mdDateLocale
。
回答by ttvd94
I had same problem and came up with this simple solution with the help of moment.js. I used ng-change
attribute which fires when the date is changed.
我遇到了同样的问题,并在moment.js的帮助下提出了这个简单的解决方案。我使用ng-change
了在更改日期时触发的属性。
Inside your HTML:
在您的 HTML 中:
<md-datepicker ng-model="myDate" ng-change="dateChanged()"></md-datepicker>
Inside your controller:
在您的控制器内部:
$scope.dateChanged = function() {
this.myDate = moment(this.myDate).format('YYYY/MM/DD');
}
回答by Alex Pandrea
For angular-material
>= 5.x.x
对于angular-material
>=5.x.x
The recommended way of using other custom/predefined date formats is described in the angular material documentation:
角度材料文档中描述了使用其他自定义/预定义日期格式的推荐方法:
An implementation example using MomentJSfor customizing and parsing datetime display formats:
使用MomentJS自定义和解析日期时间显示格式的实现示例:
...
import { MomentModule } from 'angular2-moment';
import { MatMomentDateModule, MomentDateAdapter, MAT_MOMENT_DATE_FORMATS } from '@angular/material-moment-adapter';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
...
// moment formats explanation: https://momentjs.com/docs/#/displaying/format/
export const MY_FORMATS = {
parse: {
dateInput: 'YYYY-MM-DD',
},
display: {
dateInput: 'YYYY-MM-DD',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'YYYY-MM-DD',
monthYearA11yLabel: 'MMMM YYYY',
},
};
...
@Component({
...
providers: [
// `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
// `MatMomentDateModule` in your applications root module. We provide it at the component level
// here, due to limitations of our example generation script.
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
// {provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS}
]
})
...
Depending on your implementation, inside the component you might also need to use:
根据您的实现,在组件内部您可能还需要使用:
date = new FormControl(moment());
date = new FormControl(moment());
You must also install Moment library and adapter for Angular:
您还必须为 Angular 安装 Moment 库和适配器:
https://www.npmjs.com/package/angular2-moment
https://www.npmjs.com/package/angular2-moment
npm install --save angular2-moment
npm install --save angular2-moment
https://www.npmjs.com/package/@angular/material-moment-adapter
https://www.npmjs.com/package/@angular/material-moment-adapter
npm install --save @angular/material-moment-adapter
npm install --save @angular/material-moment-adapter
回答by J. Colby Fisher
I'd like to provide my solution that's 100% based off of Christiaan Westerbeek's post. I really like what he did, but I personally wanted something a bit more simplistic.
我想提供 100% 基于Christiaan Westerbeek 的帖子的解决方案。我真的很喜欢他所做的,但我个人想要一些更简单的东西。
appConfig.js
应用程序配置文件
// config params in global scope that need to be set outside of Angular (due to Angular limitiations)
var appConfig = {
// enables the dynamic setting of md-datepicker display masks (eg. when user changes language from English to Spanish)
date: {
// default mask
format: "MM/dd/yyyy",
// md-datepicker display format
mdFormatDate: function (date) {
if (date && date instanceof Date) {
return date.format(appConfig.date.format);
} else {
return null;
}
}
}
};
app.material.config.js
app.material.config.js
// set angular material config
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
// this is a global object set inside appConfig.js
$mdDateLocaleProvider.formatDate = appConfig.date.mdFormatDate;
}]);
some service file that deals with localization/translations/etc
一些处理本地化/翻译/等的服务文件
// inside the service where you'd track the language/locale change
service._updateConfigDateFormat = function (theNewDateFormat) {
// where theNewDateFormat is something like 'yyyy/MM/dd' or whatever
daepConfig.date.format = theNewDateFormat;
};
It should be noted that this solution will notlive re-format your md-datepicker's display values. It will only work when the model changes values.
应该注意的是,此解决方案不会实时重新格式化您的 md-datepicker 的显示值。它仅在模型更改值时起作用。