2017-04-27 136 views
4

我是'角度2'和'角度js材料'中的新角色。我在我的項目中使用material-datepicker。設置材料日期選擇器的角度2的日期格式

這是我的日期選擇器代碼

<material-datepicker placeholder="Select Date" [(date)]="currentDate" name="currentDate" required></material-datepicker> 

這將是在瀏覽器的顯示,如下所示。

enter image description here

我擔心的是日期格式問題。如何從2017年4月27日設定的日期格式,以4月27日2017年

+0

您正在使用哪個日期選擇器?你能鏈接嗎?如果你正在使用angular-material(angular 1.x),請參閱['$ mdDateLocaleProvider'](https://material.angularjs.org/latest/api/service/$mdDateLocaleProvider) – VincenzoC

+0

@VincenzoC這是我正在使用的鏈接https://www.pincer.io/npm/libraries/angular2-material-datepicker –

+0

您是否嘗試過使用'dateFormat'選項?你可以嘗試在你的'' – VincenzoC

回答

0

可以使用dateFormat選項的指定MMMM DD YYYY令牌其中:

  • MMMM是名月
  • DD是當天一個月
  • YYYY

momentjs docs規定的一年。

您的代碼將是這樣的:

<material-datepicker [dateFormat]="'MMMM DD YYYY'" placeholder="Select Date" [(date)]="currentDate" name="currentDate" required></material-datepicker> 
+0

上添加'dateFormat =「MMMM DD YYYY''我試過這個,但是對我沒有幫助。 –

+0

@LibinCJacob抱歉,'placeholder'選項是否有效?你有沒有嘗試過使用'[dateFormat] =「MMMM DD YYYY」'(添加方括號)? – VincenzoC

+0

對不起@VincenzoC ....它不起作用 –

0

材料日期選擇器是用時間來格式化日期,所以如果你只給該模式的時刻接受你可以得到你想要的格式的日期。 [dateFormat]="'LL'"

+0

如何將datepicker的輸出從iso更改爲其他值,讓day toLocaleString() –

0

在角2 MD日期選擇器,您可以更改日期的格式如下:

創建延伸NativeDateAdapter組件:

import { Component, OnInit } from '@angular/core'; 
import { NativeDateAdapter } from '@angular/material'; 
export class DateAdapterComponent extends NativeDateAdapter { 
    format(date: Date, displayFormat: Object): string { 
     let day = date.getDate(); 
     let month = date.getMonth(); 
     let year = date.getFullYear(); 

     if (displayFormat == "input") { 
      return this._toString(month) + ' '+ this._to2digit(day) + ',' + year; 
     } else { 
      return this._toString(month) + ' ' + year; 
     } 
    } 

    private _to2digit(n: number) { 
     return ('00' + n).slice(-2); 
    } 

    private _toString(n: number) { 
     let month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; 
     return month[n]; 
    } 
} 

添加日期格式常數您的應用程序模塊:

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'}, 
    } 
}; 

和供應商,添加日期適配器和日期格式:

providers: [ {provide: DateAdapter, useClass: DateAdapterComponent}, 
       {provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS}], 
相關問題