Home > Enterprise >  angular date range 2 date logic (excluding weekends)
angular date range 2 date logic (excluding weekends)

Time:07-21

Currently I have a mat date picker range. The logic is the min date on the calendar that the user can select is 2 days so for example date today is 20(july 20, 2022) then the min date is 22(july 22, 2022) because it is 2.

But if the next 2 days are weekends for example our current date is let us say today is 22(july 22, 2022) if you look at the calendar 23 and 24 are weekends so it must be excluded so 2 would start from 22(july 22, 2022) and 25(july 25, 2022) so the min date would be 26(july 26, 2022).

How would we handle this logic on a date picker ?

#https://stackblitz.com/edit/angular-byrmnt-setsza?file=src/app/date-range-picker-overview-example.ts,src/index.html,src/app/date-range-picker-overview-example.html

#html

<mat-form-field>
  <mat-label>Enter a date range</mat-label>
  <mat-date-range-input [rangePicker]="picker" [dateFilter]="weekendsDatesFilter">
    <input matStartDate matInput placeholder="Start date" >
    <input matEndDate matInput placeholder="End date">
  </mat-date-range-input>
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>

#ts

export class DateRangePickerOverviewExample {
  currentDate = new Date();

  ngOnInit(): void { 
    this.currentDate = new Date(this.currentDate.setDate(this.currentDate.getDate()   2));
  }

  weekendsDatesFilter = (d: Date): boolean => {
    const day = d.getDay();
    /* Prevent Saturday and Sunday for select. */
    return day !== 0 && day !== 6;
  };
}

CodePudding user response:

Can you please check this click here? I hope this will work for you.

 import { Component } from '@angular/core';
    
    @Component({
      selector: 'date-range-picker-overview-example',
      templateUrl: 'date-range-picker-overview-example.html',
      styleUrls: ['date-range-picker-overview-example.css'],
    })
    export class DateRangePickerOverviewExample {
      currentDate = new Date();
    
      ngOnInit(): void {
        this.currentDate = new Date(
          this.currentDate.setDate(this.currentDate.getDate()   2)
        );
        !this.weekendsDatesFilter(this.currentDate) && this.weekendsHandler();
      }
    
      weekendsDatesFilter = (d: Date): boolean => {
        const day = d.getDay();
        /* Prevent Saturday and Sunday for select. */
        return day !== 0 && day !== 6;
      };
      weekendsHandler() {
        this.currentDate = new Date(
          this.currentDate.setDate(this.currentDate.getDate()   1)
        );
        !this.weekendsDatesFilter(this.currentDate) && this.weekendsHandler();
      }
    }
  • Related