Currently I have a mat date picker range. The logic is the min date on the calendar that the user can select is + 2 full days but exlude the counting of weekends for example
If today is 25(July 25, 2022 ) then the current date([min]=”currentDate”) should be 28 which is thursday July 28, 2022.
If today is 26(July 26, 2022 ) then the current date([min]=”currentDate”) should be 28 which is thursday July 29, 2022.
But if for example if its friday it should not include the count of weekends for example today is 29(July 29, 2022 ) then the current date([min]=”currentDate”)should be Wednesday 3(August 03, 2022 .
And same logic goes to every dates.
Any idea guys how would we make it possible with the calendar? Thanks.
#blitz
https://stackblitz.com/edit/angular-byrmnt-setsza?file=src%2Fapp%2Fdate-range-picker-overview-example.ts,src%2Findex.html,src%2Fapp%2Fdate-range-picker-overview-example.html
#html
<mat-form-field> <mat-label>Enter a date range</mat-label> <mat-date-range-input [min]="currentDate" [rangePicker]="picker" > <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 code
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; // }; }
Advertisement
Answer
getMinDate(date: any) { return dateCompare=[1,2,3,4,5,6,7].map(x=> new Date(date.getTime()+(24*60*60*1000*x))) .filter(x=>x.getDay()!=6 && x.getDay()!=0) .find((x,i)=>i==1) }
Update explained
The code create an array of 7 dates (each element in the array one day).
[1,2,3,4,5,6,7].map(x=> new Date(date.getTime()+(24*60*60*1000*x)))
Transform the array [1,2,3,4,5..] in an array of dates, e.g. [2022-07-29,2022-07-30,2022-07-31,2022-08-01,2022-08-02…]
Then filter and only get the dates who are not sunday nor saturday.
.filter(x=>x.getDay()!=6 && x.getDay()!=0)
the new array becomes like [2022-07-29,2022-08-01,2022-08-02,…]
Finally gets the element in position 2 (in the array the position 1 is the index 0, the position 2 is the index 1…)
.find((x,i)=>i==1)
gets 2022-08-01
If we need one day not sunday or saturday we can change the “i==1” by “i==2”.