angularangular-material2

MatDatePicker start week on monday


There is any way to configure the md-datepicker to start week on monday? By default it start on Sunday and there isn't any specification who to change this.


Solution

  • You have to build a custom DateAdapter. A custom DateAdapter is a class that implements the DateAdapter interface (it's actually an abstract class that should be extended). It must have a bunch of predefined method implementations and have to be registered as a useClass for the DateAdapter provider.

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

    The date adapter tells the date picker things like how to store dates/times internally, how to present them in the input, and other things.

    @angular/material provided four classes that extend the DateAdapter abstract class: NativeDateAdapter, MomentDateAdapter, LuxonDateAdapter and DateFnsAdapter. They tell MatDatepicker how to work with the javascript native Date object and moment object, respectively. I'll talk about the javascript native Date object, but the same principles apply to any date representation. The javascript Date object has some limitations (for example, it's not possible to tell it how you want to present dates). To make a long story short: extend the Material provided NativeDateAdapter and override the methods you need. What you want to do is shown in this stackblitz demo (basically you want to override a method of the NativeDateAdapter: getFirstDayOfWeek : () => number) and I'll give a little overview afterwards.

    getFirstDayOfWeek(): number {
      return 1;
    }
    

    In the demo, you will see a custom-date-adapter.ts. This is where you should extend the NativeDateAdapter, overriding two functions:

    1) parse: (value: any) => Date | null
    2) getFirstDayOfWeek: ()=> number
    

    The first function is meant to a) among other things, create a Date object from what the user chose in the calendar, and b) parse what is typed in the input to a Date object.

    The second function (getFirstDayOfWeek) tells the calendar to start on a specific weekday (0 - Sunday, 1 - Monday, 2 - Tuesday ...).

    Also, there's an interesting format: (date: Date, displayFormat: Object) => string function available to be implemented/overridden that allows you to define the format the date string must be shown in the input after being selected from the calendar popup.

    In the demo, in the main.ts you must tell Angular that there is a custom date adapter to use (look at the providers array). In this case, I built this demo to work with Brazilian Portuguese (look at the main.ts constructor, for the date.setLocale('pt-BR')). Over here, we present dates as dd/MM/yyy, knowing Monday == "Segunda-Feira" in portuguese. :D

    Hope it helps.