javascriptangularangular-materialdatepickerlocale

Angular getLocaleFirstDayOfWeek('en-FR') returns 0 (Sunday) as the start day of the week where as it returns 1 (Monday) for en-NL


I need to show the start day of the week based on locale and customise the date picker to show the week days. Since NativeAdaptor always returns Sunday as the week start day, a custom adaptor is written for overriding the native getFirstDayOfWeek() method with angular provided https://angular.io/api/common/getLocaleFirstDayOfWeek. Below is the CustomAdaptor class

import { getLocaleFirstDayOfWeek } from '@angular/common';
import { Inject, Injectable, LOCALE_ID } from '@angular/core';
import { NativeDateAdapter } from '@angular/material/core';
@Injectable()
export class CustomDateAdapter extends NativeDateAdapter {
  constructor(
    @Inject(LOCALE_ID) public locale: string
  ) {
    super(locale);
  }
  override getFirstDayOfWeek(): number {
    return getLocaleFirstDayOfWeek(this.locale);
  }
}

This CustomAdaptor works fine for 'nl-NL' and 'fr-FR' which returns Monday as the start day of the week. But getLocaleFirstDayOfWeek('en-FR') returns Sunday and getLocaleFirstDayOfWeek('en-NL') returns Monday. So the application is inconsistent. While comparing with the https://www.google.com/travel/flights?gl=NL 'en-NL' and 'en-FR' should return Monday as the start day of the week. So which is the single source of truth for getting the first day of the week?. Or is there any correction required in my implementation?


Solution

  • En-fr is an invalid locale, check the full list of locales to use a valid one, so it fallsback to the default value which is zero (Sunday)


    As per the angualar docs,

    getLocaleFirstDayOfWeek(FUNCTION)

    Retrieves the first day of the week for the given locale.

    getLocaleFirstDayOfWeek(locale: string): WeekDay

    Parameters

    locale string -> A locale code for the locale format rules to use.

    Returns

    WeekDay: A day index number, using the 0-based week-day index for en-US (Sunday = 0, Monday = 1, ...). For example, for fr-FR, returns 1 to indicate that the first day is Monday.

    The fix will be to simply return zero always!

      override getFirstDayOfWeek(): number {
        return 0;
      }
    

    Source Code: angular/packages/common/locales /closure-locale.ts

    Here the 8th index is firstDay of the week number of property locale_fr which is 1 (Monday)!