Angular 2 Material 2 datepicker日期格式

时间:2017-06-09 08:31:05

标签: javascript angular angular-material2

我需要帮助。我不知道如何更改材料2 datepicker的日期格式。我已阅读文档,但我不明白我实际需要做什么。默认情况下,datepicker提供的输出日期格式为f.e。:6/9/2017

我想要实现的是将格式更改为2017年6月9日或其他任何内容。

文档https://material.angular.io/components/component/datepicker对我没有任何帮助。 提前致谢

14 个答案:

答案 0 :(得分:34)

这是我找到的唯一解决方案:

首先,创建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 )中实现。

答案 1 :(得分:28)

Igor的回答对我没有用,所以我直接问Angular 2 Material's github,有人给了我那个对我有用的答案:

  1. 首先编写自己的适配器:

    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();
        }
    }
    
  2. 创建日期格式:

    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' },
        }
    };
    
  3. 将这两个提供给您的模块

    providers: [
            {
                provide: DateAdapter, useClass: AppDateAdapter
            },
            {
                provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
            }
        ]
    
  4. 更多信息here

答案 2 :(得分:10)

对我有用的工作是:

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')。

答案 3 :(得分:10)

您只需提供自定义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
}]

工作code

答案 4 :(得分:3)

Robouste工作得很完美!!

我做得很轻松(Angular 4&#34; @ angular / material&#34;:&#34; ^ 2.0.0-beta.10&#34;) 首先制作了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 {}

答案 5 :(得分:3)

为日期格式创建一个常量。

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 }
]

答案 6 :(得分:2)

为什么不使用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() {}
}

答案 7 :(得分:1)

我使用@ igor-janković提出的解决方案并遇到了“错误:未捕获(承诺):TypeError:无法读取未定义的属性'dateInput'”的问题。我意识到这个问题是因为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'},
   }
};

通过上述修改,解决方案对我有用。

此致

答案 8 :(得分:1)

角形材料日期将返回以下格式(只需通过console.log即可查看)

Moment {_isAMomentObject:true,_i:{…},_isUTC:false,_pf:{…},_locale:Locale,…} _d:2021年1月28日星期四00:00:00 GMT + 0800(新加坡标准时间){}

_i:{年:2021,月:0,日期:28}

_isAMomentObject:true ........

所以我通过使用模板文字将其转换为短日期

due_date = ${due_date._i.year}-${due_date._i.month + 1}-${due_date._i.date}

您将获得“ YYYY-MM-DD”格式

答案 9 :(得分:0)

创建文件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>

答案 10 :(得分:0)

Arthur z和Gil Epshtain的原始想法,我将moment更改为date-fns。 经过角@angular/material": "^10.0.2测试。

创建CustomDateAdapter.ts并像这样实现它:

import { NativeDateAdapter } from "@angular/material/core";
import { format } from 'date-fns';
import { es } from 'date-fns/locale'

export class CustomDateAdapter extends NativeDateAdapter {
    format(date: Date, displayFormat: Object): string {
        var formatString = (displayFormat === 'input')? 'DD.MM.YYYY' : 'dd-MM-yyyy';
        return format(date, formatString, {locale: es});
    }
}

在您的 app.module.ts 中:

import { DateAdapter } from '@angular/material';

providers: [
    ...
    {
        provide: DateAdapter, useClass: CustomDateAdapter
    },
    ...
]

答案 11 :(得分:0)

这对我有用!

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';

// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment} from 'moment';

const moment = _rollupMoment || _moment;

// See the Moment.js docs for the meaning of these formats:
// https://momentjs.com/docs/#/displaying/format/
export const MY_FORMATS = {
parse: {
    dateInput: 'LL',
},
display: {
    dateInput: 'LL',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
},
};

/** @title Datepicker with custom formats */
@Component({
selector: 'datepicker-formats-example',
templateUrl: 'datepicker-formats-example.html',
providers: [
    // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your
    // application's 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, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
    },

    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
],
})
export class YourDatepickerUsedComponent {
    date = new FormControl(moment());
}

链接:https://material.angular.io/components/datepicker/examples并搜索“具有自定义格式的日期选择器”

答案 12 :(得分:-1)

来自文档:

... various imports
ReactDOM.render(
    <Router>
        <Switch>
            <Route path="/" component={withTracker(App)}/>
        </Switch>
    </Router>
    , document.getElementById('root'))
  1. 向NgModule添加所需。
  2. 创建您自己的格式 - MY_NATIVE_DATE_FORMATS

答案 13 :(得分:-1)

这是我使用MAT_NATIVE_DATE_FORMATS使用最少代码的解决方案。

  1. 声明您自己的日期格式
import { MatDateFormats, MAT_NATIVE_DATE_FORMATS } from '@angular/material';

export const GRI_DATE_FORMATS: MatDateFormats = {
  ...MAT_NATIVE_DATE_FORMATS,
  display: {
    ...MAT_NATIVE_DATE_FORMATS.display,
    dateInput: {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    } as Intl.DateTimeFormatOptions,
  }
};
  1. 使用它们
@Component({
  selector: 'app-vacation-wizard',
  templateUrl: './vacation-wizard.component.html',
  styleUrls: ['./vacation-wizard.component.scss'],
  providers: [
    { provide: MAT_DATE_FORMATS, useValue: GRI_DATE_FORMATS },
  ]
})

别忘了设置适当的语言!

this.adapter.setLocale(this.translate.currentLang);

仅此而已!