You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Update NativeDateAdapter to use the new i18n api #8100
What is the use-case or motivation for changing an existing behavior?
In Angular v5 we have removed the dependency on the intl API to use CLDR data instead. We've also added a new I18n API that can be used by libraries for such a case.
It's very easy to rewrite the NativeDateAdapter to use this instead of intl. The only problem is that Material requires a few formats that are not yet supported by the API.
We can write an adapter that does partial matching, but it'd be better to wait for angular/angular#19823 to be resolved first.
Reacted by Sylvain Dumont, Deniss Kozlovs, Rafael Santana, Luiz Machado, Sergey Fetiskin, Ilia Ametov, Daniel Kimmich and Belan
Here is a complete working example of the new NativeDateAdapter
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */import{DateAdapter,MAT_DATE_LOCALE,MatDateFormats}from'@angular/material';import{Inject,Optional}from'@angular/core';import{DatePipe,FormStyle,getLocaleDayNames,getLocaleFirstDayOfWeek,getLocaleMonthNames,TranslationWidth}from'@angular/common';constDEFAULT_DATE_NAMES=range(31,i=>String(i+1));/** * Matches strings that have the form of a valid RFC 3339 string * (https://tools.ietf.org/html/rfc3339). Note that the string may not actually be a valid date * because the regex will match strings and with out of bounds month, date, etc. */constISO_8601_REGEX=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|(?:(?:\+|-)\d{2}:\d{2}))?)?$/;exportconstMAT_NATIVE_DATE_FORMATS: MatDateFormats={parse: {dateInput: null,},display: {dateInput: 'shortDate',monthYearLabel: 'MMM yyyy',// tododateA11yLabel: 'longDate',monthYearA11yLabel: 'MMMM yyyy',// todo}};exportclassNativeDateAdapterextendsDateAdapter<Date>{privatedatePipe: DatePipe;constructor(@Optional() @Inject(MAT_DATE_LOCALE)publicmatDateLocale: string){super();super.setLocale(this.matDateLocale);this.datePipe=newDatePipe(matDateLocale);}getYear(date: Date): number{returndate.getFullYear();}getMonth(date: Date): number{returndate.getMonth();}getDate(date: Date): number{returndate.getDate();}getDayOfWeek(date: Date): number{returndate.getDay();}getMonthNames(style: 'long'|'short'|'narrow'): string[]{returngetLocaleMonthNames(this.matDateLocale,FormStyle.Format,this.getStyle(style));}getDateNames(): string[]{returnDEFAULT_DATE_NAMES;}getDayOfWeekNames(style: 'long'|'short'|'narrow'): string[]{returngetLocaleDayNames(this.matDateLocale,FormStyle.Format,this.getStyle(style));}getYearName(date: Date): string{returnString(this.getYear(date));}getFirstDayOfWeek(): number{returngetLocaleFirstDayOfWeek(this.matDateLocale);}getNumDaysInMonth(date: Date): number{returnthis.getDate(this._createDateWithOverflow(this.getYear(date),this.getMonth(date)+1,0));}clone(date: Date): Date{returnthis.createDate(this.getYear(date),this.getMonth(date),this.getDate(date));}createDate(year: number,month: number,date: number): Date{// Check for invalid month and date (except upper bound on date which we have to check after// creating the Date).if(month<0||month>11){throwError(`Invalid month index "${month}". Month index has to be between 0 and 11.`);}if(date<1){throwError(`Invalid date "${date}". Date has to be greater than 0.`);}constresult=this._createDateWithOverflow(year,month,date);// Check that the date wasn't above the upper bound for the month, causing the month to overflowif(result.getMonth()!==month){throwError(`Invalid date "${date}" for month with index "${month}".`);}returnresult;}today(): Date{returnnewDate();}parse(value: any,parseFormat: any): Date|null{// We have no way using the native JS Date to set the parse format or locale, so we ignore these parameters.if(typeofvalue==='number'){returnnewDate(value);}returnvalue ? newDate(Date.parse(value)) : null;}format(date: Date,displayFormat: string): string{if(!this.isValid(date)){throwError('I18nDateAdapter: Cannot format invalid date.');}returnthis.datePipe.transform(date,displayFormat);}addCalendarYears(date: Date,years: number): Date{returnthis.addCalendarMonths(date,years*12);}addCalendarMonths(date: Date,months: number): Date{letnewDate=this._createDateWithOverflow(this.getYear(date),this.getMonth(date)+months,this.getDate(date));// It's possible to wind up in the wrong month if the original month has more days than the new// month. In this case we want to go to the last day of the desired month.// Note: the additional + 12 % 12 ensures we end up with a positive number, since JS % doesn't// guarantee this.if(this.getMonth(newDate)!==((this.getMonth(date)+months)%12+12)%12){newDate=this._createDateWithOverflow(this.getYear(newDate),this.getMonth(newDate),0);}returnnewDate;}addCalendarDays(date: Date,days: number): Date{returnthis._createDateWithOverflow(this.getYear(date),this.getMonth(date),this.getDate(date)+days);}toIso8601(date: Date): string{return[date.getUTCFullYear(),this._2digit(date.getUTCMonth()+1),this._2digit(date.getUTCDate())].join('-');}fromIso8601(iso8601String: string): Date|null{// The `Date` constructor accepts formats other than ISO 8601, so we need to make sure the// string is the right format first.if(ISO_8601_REGEX.test(iso8601String)){constd=newDate(iso8601String);if(this.isValid(d)){returnd;}}returnnull;}isDateInstance(obj: any): boolean{returnobjinstanceofDate;}isValid(date: Date): boolean{return!isNaN(date.getTime());}privategetStyle(style: 'long'|'short'|'narrow'): TranslationWidth{switch(style){case'long':
returnTranslationWidth.Wide;case'short':
returnTranslationWidth.Abbreviated;case'narrow':
returnTranslationWidth.Narrow;}}/** * Pads a number to make it two digits. * @param n The number to pad. * @returns The padded number. */private_2digit(n: number){return('00'+n).slice(-2);}/** Creates a date but allows the month and date to overflow. */private_createDateWithOverflow(year: number,month: number,date: number){constresult=newDate(year,month,date);// We need to correct for the fact that JS native Date treats years in range [0, 99] as// abbreviations for 19xx.if(year>=0&&year<100){result.setFullYear(this.getYear(result)-1900);}returnresult;}}/** Creates an array and fills it with values. */functionrange<T>(length: number,valueFunction: (index: number)=>T): T[]{constvaluesArray=Array(length);for(leti=0;i<length;i++){valuesArray[i]=valueFunction(i);}returnvaluesArray;}
The only issues here are the formats display.monthYearLabel & display.monthYearA11yLabel which are fixed, it requires fixing angular/angular#19823 first
I agree, right now this is very strange situation with locale.
Angular 5+ work with locale by registerLocaleData.
Material 5+ work with locale by Intl API.
I personally don't like Intl API, because it's always different results.
And technic with registerLocaleData more strictly and making expected result (big thanks to angular team).
Anyway here is the main problems:
Example locale: cs
Example date: 5 Jan 2018
format problem
Czech shortDate in angular datePipe return: 05.01.18
Czech date format in material return: 5. 1. 2018.
Yes, this is not a bug, but i believe for user experience better to keep date formats in one way.
parse problem
Material method parse for string values call Date.parse() method.
This method expected: RFC2822 standard. It's mean if user tries to change some value in Czech date inside input, this will be a problem. Because this is a not RFC2822.
If user change month to Feb: 5. 1. 2018 > 5. 2. 2018, than you get date: 1 May 2018.
My opinion this is not good way of parsing, and for UI this is bug.
Ok after all i wrote my own adapter that extend NativeDateAdapter like @ocombe. I override some methods to support registerLocaleData format.
And fix 2nd problem with parse method and keep Date.parse() compatibility, I hope this helps someone.
import{NativeDateAdapter}from'@angular/material';import{Inject,LOCALE_ID}from'@angular/core';import{DatePipe,FormStyle,getLocaleDayNames,getLocaleFirstDayOfWeek,getLocaleMonthNames,TranslationWidth}from'@angular/common';constDEFAULT_DATE_NAMES: string[]=Array.from(Array(31).keys()).map(i=>(i+1).toString());exportclassMyDateAdapterextendsNativeDateAdapter{privatedatePipe: DatePipe;privatestyleMap={long: TranslationWidth.Wide,short: TranslationWidth.Abbreviated,narrow: TranslationWidth.Narrow};constructor(@Inject(LOCALE_ID)locale: string){super(locale);this.datePipe=newDatePipe(locale);}getDateNames(): string[]{returnDEFAULT_DATE_NAMES;}getMonthNames(style: 'long'|'short'|'narrow'): string[]{returngetLocaleMonthNames(this.locale,FormStyle.Format,this.styleMap[style]);}getDayOfWeekNames(style: 'long'|'short'|'narrow'): string[]{returngetLocaleDayNames(this.locale,FormStyle.Format,this.styleMap[style]);}getFirstDayOfWeek(): number{returngetLocaleFirstDayOfWeek(this.locale);}format(date: Date,displayFormat: string): string{if(!this.isValid(date)){throwError('I18nDateAdapter: Cannot format invalid date.');}displayFormat='shortDate';returnthis.datePipe.transform(date,displayFormat);}parse(value: any): Date|null{consttimestamp=typeofvalue==='number'
? value
: this.parseByFormat(value);returnisNaN(timestamp)
? null
: newDate(timestamp);}/** * This method helpts parse date value by locale format * @param value * @returns {number} */privateparseByFormat(value: any): number|null{if(typeofvalue!=='string'){returnnull;}// trick to find 12,13,14 positionsconstformatted=this.format(newDate('2014-12-13'),'shortDate');constdelimiter=formatted.match(/\D/);// delimiter not foundif(!delimiter){returnDate.parse(value);}// split valueconstvalueItems=value.split(delimiter[0]);constformattedItems=formatted.split(delimiter[0]);// delimiter is not the same as user inputif(formattedItems.length<=2||valueItems.length<=2){returnDate.parse(value);}// find indexes of positionsconstyearMatch=formatted.match(/[0-9]*14/);constmonthIndex=formattedItems.indexOf('12');constdayIndex=formattedItems.indexOf('13');letyearIndex=-1;if(yearMatch){yearIndex=formattedItems.indexOf(yearMatch[0]);}// all index for year/month/day foundif(yearIndex!==-1&&monthIndex!==-1&&dayIndex!==-1){valueItems.map(val=>val.replace(/\D/g,''));constyear=valueItems[yearIndex];constmonth=valueItems[monthIndex];constday=valueItems[dayIndex];// fix problem with none four-digit year numberconstfullYear=(newDate()).getFullYear().toString().substr(0,4-year.length)+year;value=fullYear+'-'+month+'-'+day;}returnDate.parse(value);}}
I hope in feature releases google will add support of Material Date Adapter that based on format provided from registerLocaleData. This feature/request very required.
Activity
jelbourn commentedon Oct 29, 2017
@ocombe can you give an example of something specific that would change?
ocombe commentedon Oct 30, 2017
Sure, search for any block of text with
SUPPORTS_INTL_APIin https://github.com/angular/material2/blob/master/src/lib/core/datetime/native-date-adapter.ts, you could remove it and use the Angular i18n API instead.Here is an example for the method
getMonthNames.Original:
After change:
Here is a complete working example of the new NativeDateAdapter
The only issues here are the formats
display.monthYearLabel&display.monthYearA11yLabelwhich are fixed, it requires fixing angular/angular#19823 firstdenirun commentedon Jan 5, 2018
I agree, right now this is very strange situation with locale.
Angular 5+ work with locale by registerLocaleData.
Material 5+ work with locale by Intl API.
I personally don't like Intl API, because it's always different results.
And technic with registerLocaleData more strictly and making expected result (big thanks to angular team).
Anyway here is the main problems:
Example locale: cs
Example date: 5 Jan 2018
format problem
Czech shortDate in angular datePipe return: 05.01.18
Czech date format in material return: 5. 1. 2018.
Yes, this is not a bug, but i believe for user experience better to keep date formats in one way.
parse problem
Material method parse for string values call
Date.parse()method.This method expected: RFC2822 standard. It's mean if user tries to change some value in Czech date inside input, this will be a problem. Because this is a not RFC2822.
If user change month to Feb: 5. 1. 2018 > 5. 2. 2018, than you get date: 1 May 2018.
My opinion this is not good way of parsing, and for UI this is bug.
Ok after all i wrote my own adapter that extend NativeDateAdapter like @ocombe. I override some methods to support registerLocaleData format.
And fix 2nd problem with parse method and keep Date.parse() compatibility, I hope this helps someone.
* Don't forget to register adapter in @NgModule
* Don't forget to register your locale in registerLocaleData
I hope in feature releases google will add support of Material Date Adapter that based on format provided from registerLocaleData. This feature/request very required.
fetis commentedon Jan 28, 2021
this issue is open for 3 years so far with a working example to fix, but still is not resolved 🤷♂️