Angular 2 Материал 2 формат даты даты
Мне нужна помощь. Я не знаю, как изменить формат даты материала 2 datepicker. Я читал документацию, но я не понимаю, что мне действительно нужно делать. Формат выходной даты, который предоставляет datepicker по умолчанию: f.e.: 6/9/2017
Я пытаюсь изменить формат до 9 июня 2017 года или любой другой.
Документация https://material.angular.io/components/component/datepicker не помогает мне вообще.
Спасибо заранее
Ответы
Ответ 1
Вот единственное решение, которое я нашел для этого:
Сначала создайте const:
const MY_DATE_FORMATS = {
parse: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
},
display: {
// dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
dateInput: 'input',
monthYearLabel: {year: 'numeric', month: 'short'},
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
}
};
Затем вам нужно расширить NativeDateADapter:
export class MyDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat == "input") {
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return this._to2digit(day) + '/' + this._to2digit(month) + '/' + year;
} else {
return date.toDateString();
}
}
private _to2digit(n: number) {
return ('00' + n).slice(-2);
}
}
В функции формата вы можете выбрать любой желаемый формат
И последний шаг, вы должны добавить его в поставщиков модулей:
providers: [
{provide: DateAdapter, useClass: MyDateAdapter},
{provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS},
],
И что это. Я не могу поверить, что нет простого способа изменить формат даты через @Input, но пусть надеется, что он будет реализован в некоторой будущей версии материала 2 (в настоящее время beta 6).
Ответ 2
Ответ Игоря не сработал для меня, поэтому я спросил напрямую о Angular 2 Material github, и кто-то дал мне тот ответ, который работал для меня:
-
Сначала напишите свой собственный адаптер:
import { NativeDateAdapter } from "@angular/material";
export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return '${day}-${month}-${year}';
}
return date.toDateString();
}
}
-
Создайте свой формат даты:
export const APP_DATE_FORMATS =
{
parse: {
dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
},
display: {
dateInput: 'input',
monthYearLabel: { year: 'numeric', month: 'numeric' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' },
}
};
-
Предоставьте эти два для вашего модуля
providers: [
{
provide: DateAdapter, useClass: AppDateAdapter
},
{
provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
}
]
Больше информации здесь
Ответ 3
Вам просто нужно предоставить пользовательский MAT_DATE_FORMATS
export const APP_DATE_FORMATS = {
parse: {dateInput: {month: 'short', year: 'numeric', day: 'numeric'}},
display: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'},
monthYearLabel: {year: 'numeric'}
}
};
и добавить его в провайдеры.
providers: [{
provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
}]
Рабочий код
Ответ 4
Работа, которая работает для меня, это:
my.component.html:
<md-input-container>
<input mdInput disabled [ngModel]="someDate | date:'d-MMM-y'" >
<input mdInput [hidden]='true' [(ngModel)]="someDate"
[mdDatepicker]="picker">
<button mdSuffix [mdDatepickerToggle]="picker"></button>
</md-input-container>
<md-datepicker #picker></md-datepicker>
my.component.ts :
@Component({...
})
export class MyComponent implements OnInit {
....
public someDate: Date;
...
Итак, теперь вы можете иметь формат (пример. d-MMM-y), который лучше всего подходит вам.
Ответ 5
Существует высокая вероятность того, что вы уже используете библиотеку, которая предоставляет удобный способ манипулирования (анализ, проверка, отображение и т.д.) Датами и временем в JavaScript. Если вы этого не сделаете, взгляните на один из них, например moment.js.
Реализация вашего собственного адаптера с помощью moment.js будет выглядеть следующим образом.
Создайте CustomDateAdapter.ts и реализуйте его следующим образом:
import { NativeDateAdapter } from "@angular/material";
import * as moment from 'moment';
export class CustomDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
moment.locale('ru-RU'); // Choose the locale
var formatString = (displayFormat === 'input')? 'DD.MM.YYYY' : 'LLL';
return moment(date).format(formatString);
}
}
В вашем app.module.ts:
import { DateAdapter } from '@angular/material';
providers: [
...
{
provide: DateAdapter, useClass: CustomDateAdapter
},
...
]
Это. Просто, легко и не нужно изобретать велосипеды.
Ответ 6
Робуст работал отлично!
Я сделал простой (Angular 4 "@angular/material": "^ 2.0.0-beta.10" )
сделанный datepicker.module.ts
import { NgModule } from '@angular/core';
import { MdDatepickerModule, MdNativeDateModule, NativeDateAdapter, DateAdapter, MD_DATE_FORMATS } from '@angular/material';
class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${year}-${month}-${day}`;
} else {
return date.toDateString();
}
}
}
const APP_DATE_FORMATS = {
parse: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
},
display: {
// dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
dateInput: 'input',
monthYearLabel: {year: 'numeric', month: 'short'},
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
}
};
@NgModule({
declarations: [ ],
imports: [ ],
exports: [ MdDatepickerModule, MdNativeDateModule ],
providers: [
{
provide: DateAdapter, useClass: AppDateAdapter
},
{
provide: MD_DATE_FORMATS, useValue: APP_DATE_FORMATS
}
]
})
export class DatePickerModule {
}
просто импортируйте его (app.module.ts)
import {Component, NgModule, VERSION, ReflectiveInjector} from '@angular/core'//NgZone,
import { CommonModule } from '@angular/common';
import {BrowserModule} from '@angular/platform-browser'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';
import { DatePickerModule } from './modules/date.picker/datepicker.module';
@Component({
selector: 'app-root',
template: `
<input (click)="picker.open()" [mdDatepicker]="picker" placeholder="Choose a date" [(ngModel)]="datepicker.SearchDate" >
<md-datepicker-toggle mdSuffix [for]="picker"></md-datepicker-toggle>
<md-datepicker #picker touchUi="true" ></md-datepicker>
`,
})
export class App{
datepicker = {SearchDate:new Date()}
constructor( ) {}
}
@NgModule({
declarations: [ App ],
imports: [ CommonModule, BrowserModule, BrowserAnimationsModule, FormsModule, DatePickerModule],
bootstrap: [ App ],
providers: [ ]//NgZone
})
export class AppModule {}
Ответ 7
Создайте константу для формата даты.
export const DateFormat = {
parse: {
dateInput: 'input',
},
display: {
dateInput: 'DD-MMM-YYYY',
monthYearLabel: 'MMMM YYYY',
dateA11yLabel: 'MM/DD/YYYY',
monthYearA11yLabel: 'MMMM YYYY',
}
};
И используйте приведенный ниже код внутри модуля приложения
providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: DateFormat }
]
Ответ 8
Почему бы не использовать Angular DatePipe?
import {Component} from '@angular/core';
import {DateAdapter, MAT_DATE_FORMATS, NativeDateAdapter} from '@angular/material';
import {FormControl} from '@angular/forms';
import {DatePipe} from '@angular/common';
export const PICK_FORMATS = {
parse: {dateInput: {month: 'short', year: 'numeric', day: 'numeric'}},
display: {
dateInput: 'input',
monthYearLabel: {year: 'numeric', month: 'short'},
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'}
}
};
class PickDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
return new DatePipe('en-US').transform(date, 'EEE, MMM dd, yyyy');
} else {
return date.toDateString();
}
}
}
@Component({
selector: 'custom-date',
template: '<mat-form-field>
<input matInput [formControl]="date" />
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>',
providers: [
{provide: DateAdapter, useClass: PickDateAdapter},
{provide: MAT_DATE_FORMATS, useValue: PICK_FORMATS}
]
})
export class DateComponent {
date = new FormControl(new Date());
constructor() {}
}
Ответ 9
Я использовал решение, предлагаемое @igor-janković, и имел проблему "Ошибка: нечистота (в обещании): TypeError: Невозможно прочитать свойство" dateInput "из undefined". Я понял, что эта проблема была вызвана тем, что MY_DATE_FORMATS
нужно объявить как type MdDateFormats
:
export declare type MdDateFormats = {
parse: {
dateInput: any;
};
display: {
dateInput: any;
monthYearLabel: any;
dateA11yLabel: any;
monthYearA11yLabel: any;
};
};
Итак, правильный способ объявления MY_DATE_FORMATS
:
const MY_DATE_FORMATS:MdDateFormats = {
parse: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
},
display: {
dateInput: 'input',
monthYearLabel: {year: 'numeric', month: 'short'},
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
}
};
С приведенной выше модификацией решение работает для меня.
Привет
Ответ 10
создать файл date.adapter.ts
import { NativeDateAdapter, DateAdapter, MAT_DATE_FORMATS, MatDateFormats } from "@angular/material";
export class AppDateAdapter extends NativeDateAdapter {
parse(value: any): Date | null {
if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
const str = value.split('/');
const year = Number(str[2]);
const month = Number(str[1]) - 1;
const date = Number(str[0]);
return new Date(year, month, date);
}
const timestamp = typeof value === 'number' ? value : Date.parse(value);
return isNaN(timestamp) ? null : new Date(timestamp);
}
format(date: Date, displayFormat: string): string {
if (displayFormat == "input") {
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return year + '-' + this._to2digit(month) + '-' + this._to2digit(day) ;
} else if (displayFormat == "inputMonth") {
let month = date.getMonth() + 1;
let year = date.getFullYear();
return year + '-' + this._to2digit(month);
} else {
return date.toDateString();
}
}
private _to2digit(n: number) {
return ('00' + n).slice(-2);
}
}
export const APP_DATE_FORMATS =
{
parse: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
},
display: {
dateInput: 'input',
monthYearLabel: 'inputMonth',
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
}
}
app.module.ts
providers: [
DatePipe,
{
provide: DateAdapter, useClass: AppDateAdapter
},
{
provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
}
]
app.component.ts
import { FormControl } from '@angular/forms';
import { DatePipe } from '@angular/common';
@Component({
selector: 'datepicker-overview-example',
templateUrl: 'datepicker-overview-example.html',
styleUrls: ['datepicker-overview-example.css'],
providers: [
DatePipe,
{
provide: DateAdapter, useClass: AppDateAdapter
},
{
provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
}
]
})
export class DatepickerOverviewExample {
day = new Date();
public date;
constructor(private datePipe: DatePipe){
console.log("anh "," " +datePipe.transform(this.day.setDate(this.day.getDate()+7)));
this.date = new FormControl(this.datePipe.transform(this.day.setDate(this.day.getDate()+7)));
console.log("anht",' ' +new Date());
}
}
app.component.html
<mat-form-field>
<input matInput [matDatepicker]="picker" placeholder="Choose a date" [formControl]="date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
Ответ 11
Из документации:
Customizing the parse and display formats
The MD_DATE_FORMATS object is just a collection of formats that the datepicker uses when parsing and displaying dates. These formats are passed through to the DateAdapter so you will want to make sure that the format objects you're using are compatible with the DateAdapter used in your app. This example shows how to use the native Date implementation from material, but with custom formats.
@NgModule({
imports: [MdDatepickerModule],
providers: [
{provide: DateAdapter, useClass: NativeDateAdapter},
{provide: MD_DATE_FORMATS, useValue: MY_NATIVE_DATE_FORMATS},
],
})
export class MyApp {}
- Добавить в NgModule.
- Создайте свой собственный формат - MY_NATIVE_DATE_FORMATS