momentjs로 Angular Material에서 md-datepicker의 형식 변경
Angular 재질은 여기 에서 찾을 수있는 새로운 날짜 선택기 구성 요소를 도입했습니다 .
이 구성 요소에서 반환 된 날짜를 yyy-mm-dd 형식으로 지정하고 싶지만 어떻게 수행되는지 잘 모르겠습니다. 검색을 $mdDateLocaleProvider
통해 사용할 수있는 것을 찾았 지만 사용 예를 찾을 수 없습니다.
누군가가 반환 한 날짜 형식을 지정하는 작업 예제를 보여줄 수 있습니까 md-datepicker
?
에 대한 문서가 $mdDateLocaleProvider
각 자료 문서에서가.
angular.module('app').config(function($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('YYYY-MM-DD');
};
});
moment.js를 사용하지 않는 경우 formatDate
날짜 형식을 지정하는 데 사용할 코드를 내부 코드로 대체하십시오 .
다음 은 Angular Material 문서의 샘플을 기반으로 한 CodePen 예제입니다.
kazuar가 지적한 문제를 해결하려면 :
불행히도 날짜를 키보드로 입력하면 작동하지 않습니다.
parseDate 메서드도 정의해야합니다. 문서에서 :
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'L', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
전체 예를 들어, 내 앱에 다음이 있습니다 (순간 사용).
$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);
};
문안 인사
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;
};
});
md-datapicker 지시문에서 '잘못된 날짜'마사지를 피하기 위해 keyborard에서 날짜를 입력하고 초기화시 null을 반환 할 때 완벽하게 작동했습니다.
$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);
};
AngularJS 1.5.9 및 moment 2.17.1에서는 런타임 중에 날짜 형식, 월 이름 및 주 이름을 완벽하게 변경할 수 있습니다.
먼저 초기 언어를 구성하십시오. (이 예에서 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') : '';
};
}
나중에 사용자가 다른 언어를 선택할 때 변경되는 언어 변수를 감시하는 기본 컨트롤러가있을 수 있습니다.
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;
});
}
를 호출하여 변경된 'L'형식을 사용하도록 이미 구성되어 있으므로 $mdDateLocale.formatDate
및 $mdDateLocale.parseDate
메서드 를 변경할 필요가 없습니다 moment.locale(newValue)
.
로케일 사용자 정의에 대한 자세한 내용은 $ mdDateLocaleProvider에 대한 문서를 참조하십시오. https://material.angularjs.org/latest/api/service/ $ mdDateLocaleProvider
보너스 : 다음은 언어 선택기의 모습입니다.
<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>
-md-dialog에서 md-DatePicker를 사용하면 $ mdDateLocaleProvider 서비스가 필요에 따라 날짜 형식을 지정하지 않습니다. md-DatePicker의 날짜 형식을 지정하려면 md-dialog의 컨트롤러에서 $ mdDateLocale을 사용해야합니다. 예를 들면-
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();
});
사용 $filter
대신 moment.js
하고 @Ian Poston 프레이머와 마침내 나를 위해 일한 다음 나를 위해 @java 디바이스로부터의 응답을 참조 :
angular
.module('App', ['ngMaterial'])
.run(function($mdDateLocale, $filter) {
$mdDateLocale.formatDate = function(date) {
return $filter('date')(date, "dd-MM-yyyy");
};
})
나는 할 수 없습니다 분사 $filter
에 .config
내가 안으로 그것을했다 그래서, 공급자 아니기 때문에 .run
함께 $mdDateLocale
.
나는 같은 문제가 있었고 moment.js 의 도움 으로이 간단한 해결책을 생각해 냈습니다 . ng-change
날짜가 변경되면 발생 하는 속성을 사용했습니다 .
HTML 내부 :
<md-datepicker ng-model="myDate" ng-change="dateChanged()"></md-datepicker>
컨트롤러 내부 :
$scope.dateChanged = function() {
this.myDate = moment(this.myDate).format('YYYY/MM/DD');
}
Christiaan Westerbeek의 게시물을 기반으로 한 100 % 솔루션을 제공하고 싶습니다 . 나는 그가 한 일을 정말 좋아하지만 개인적으로 조금 더 단순한 것을 원했습니다.
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
// set angular material config
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
// this is a global object set inside appConfig.js
$mdDateLocaleProvider.formatDate = appConfig.date.mdFormatDate;
}]);
현지화 / 번역 등을 다루는 일부 서비스 파일
// 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 not live re-format your md-datepicker's display values. It will only work when the model changes values.
For 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 MomentJS for customizing and parsing datetime display formats:
...
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());
You must also install Moment library and adapter for Angular:
https://www.npmjs.com/package/angular2-moment
npm install --save angular2-moment
https://www.npmjs.com/package/@angular/material-moment-adapter
npm install --save @angular/material-moment-adapter
If you are using the latest version of angular-material.js then use the $mdDateLocale service. This code sample uses angular's built in date filter as an alternative to using the moment.js library. See other date format options using angular's $filter service here at this link https://docs.angularjs.org/api/ng/filter/date.
// mainController.js
angular.module('app').config(function($mdDateLocale, $filter, $scope) {
// FORMAT THE DATE FOR THE DATEPICKER
$mdDateLocale.formatDate = function(date) {
return $filter('date')($scope.myDate, "mediumDate");
};
});
I used $mdDateLocaleProvider
to format it on the frond end. If you want to format date while sending it to the back end, the following worked for me :-
$filter('date')(this.date, 'MM/dd/yyyy');
I have the above in controller.
in my case I was loosing the PlaceHolder everythig works but the placeHolder was disappearing when I use custom formatting. Below lines solved my problem with placeholder.
$mdDateLocaleProvider.formatDate = function (date) {
if(date==null)
return "";
var m = moment(date);
return m.isValid() ? m.format('L') : '';
};
'Development Tip' 카테고리의 다른 글
데이터 테이블에서 열의 최소값과 최대 값을 선택하는 방법은 무엇입니까? (0) | 2020.12.09 |
---|---|
복잡한 텍스트 파일에서 쉘 변수를 대체하는 방법 (0) | 2020.12.09 |
UIMenuController가 표시되지 않음 (0) | 2020.12.09 |
한 모서리에만 테두리 반경을 사용하는 방법 (반응 네이티브)? (0) | 2020.12.09 |
/ *에서 전역 프런트 컨트롤러 서블릿을 매핑 할 때 정적 리소스에 액세스하는 방법 (0) | 2020.12.09 |